Skip to content

Commit 68bf8bc

Browse files
Add files via upload
1 parent ad7a00d commit 68bf8bc

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

week_10/Exception handling .md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
### Exception handling
2+
3+
Exception handling helps prevent our program from crashing when something goes wrong. Instead of stopping the entire program, we can use exception handling to catch errors, provide meaningful error messages, and decide what the program should do next. This makes our programs more reliable and user-friendly.
4+
## Basic Components of Exception Handling
5+
6+
- **`try` Block**: The code that might cause an exception is placed inside a `try` block. If no exceptions occur, the code runs normally.
7+
8+
- **`except` Block**: If an exception occurs in the `try` block, the control is transferred to the `except` block. Here, you can define how to handle specific exceptions.
9+
10+
- **`else` Block**: The `else` block is optional and runs only if no exceptions were raised in the `try` block. It is often used for code that should execute only if the `try` block was successful.
11+
12+
- **`finally` Block**: The `finally` block is optional and always executes, regardless of whether an exception occurred or not. It is commonly used for cleanup actions, like closing files or releasing resources.
13+
14+
- **`raise` Statement**: You can use the `raise` statement to manually trigger an exception if a certain condition occurs.
15+
16+
## Example of Exception Handling
17+
18+
```python
19+
try:
20+
# Code that might raise an exception
21+
number = int(input("Enter a number: "))
22+
result = 10 / number
23+
except ValueError:
24+
# Handles ValueError exceptions (e.g., if input is not an integer)
25+
print("Please enter a valid integer.")
26+
except ZeroDivisionError:
27+
# Handles ZeroDivisionError exceptions (e.g., if the number is zero)
28+
print("Cannot divide by zero.")
29+
else:
30+
# Executes if no exceptions were raised
31+
print(f"The result is {result}")
32+
finally:
33+
# Always executes, regardless of exceptions
34+
print("Execution complete.")
35+
```

week_10/Exception handling.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
a = 10
2+
b = 0
3+
4+
try:
5+
c = a / b # This will cause a ZeroDivisionError
6+
print(c)
7+
except ZeroDivisionError:
8+
print("Error: Cannot divide by zero.")
9+
10+
print("Future Coding")

0 commit comments

Comments
 (0)