In Python, the `try` and `except` statements are used for error handling. They allow you to catch and handle exceptions, preventing your program from crashing when an error occurs.
Here's an explanation with examples:
1. Basic Try-Except:
```python
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to handle the exception
print("Error: Division by zero")
```
In this example, the code inside the `try` block attempts to perform a division by zero, which would normally raise a `ZeroDivisionError`. The `except` block catches this specific exception and prints an error message.
2. Handling Multiple Exceptions:
```python
try:
number = int(input("Enter a number: "))
result = 10 / number
except ValueError:
print("Error: Not a valid number")
except ZeroDivisionError:
print("Error: Division by zero")
```
This example prompts the user to enter a number. If the input is not a valid integer (`ValueError`) or if the user tries to divide by zero (`ZeroDivisionError`), the appropriate error message is printed.
3. Using a Generic Exception:
```python
try:
file = open("nonexistent_file.txt", "r")
except Exception as e:
print(f"Error: {e}")
```
Catching a generic `Exception` can be useful, but it should be used carefully. It catches any exception, including system-exiting exceptions, so it may hide bugs if not used judiciously.
4. Finally Block:
```python
try:
result = 10 / 2
except ZeroDivisionError:
print("Error: Division by zero")
finally:
print("This block always executes")
```
The `finally` block is optional and is executed no matter whether an exception occurred or not. It's often used for cleanup operations.
5. Else Block:
```python
try:
number = int(input("Enter a positive number: "))
if number <= 0:
raise ValueError("Not a positive number")
except ValueError as ve:
print(f"Error: {ve}")
else:
print("You entered a positive number")
```
The `else` block is executed if no exceptions occur in the `try` block. It's often used for code that should run only when no exceptions are raised.
6. Nested Try-Except Blocks:
```python
try:
try:
result = 10 / 0
except ZeroDivisionError:
print("Inner: Division by zero")
except Exception as e:
print(f"Outer: {e}")
```
You can nest `try-except` blocks to handle exceptions at different levels of your code.
Using `try` and `except` allows you to gracefully handle errors in your Python code, improving its robustness and making it more user-friendly.
0 Comments