Python Try-Except
Handle errors gracefully using try-except blocks.
Handle errors properly.
Basic Try-Except
```python try: number = int(input("Enter number: ")) print(10 / number) except: print("Something went wrong!") ```
Specific Exceptions
```python try: number = int(input("Enter number: ")) result = 10 / number except ValueError: print("Please enter a valid number!") except ZeroDivisionError: print("Cannot divide by zero!") ```
Else and Finally
```python try: file = open("data.txt", "r") content = file.read() except FileNotFoundError: print("File not found!") else: print("File read successfully!") finally: print("This always runs") ```
Raise Exceptions
```python def check_age(age): if age < 0: raise ValueError("Age cannot be negative!") if age < 18: print("Too young") else: print("Welcome!")
check_age(25) # Welcome! ```
Remember
- Always handle specific errors - Use finally for cleanup - Don't catch all exceptions blindly