Python18 min read

Python Try Except

Handle errors professionally using try/except, specific exceptions, else/finally, and raising your own exceptions.

Michael Brown
September 17, 2025
5.7k264

In real programs, errors are normal. A user might type a wrong input, or a file might be missing. Error handling lets your program fail safely with a helpful message.

## Basic try/except

```python
try:
    number = int(input("Enter a number: "))
    print(10 / number)
except Exception:
    print("Something went wrong.")
```

This works, but it is too general. It hides the real reason.

## Catch specific exceptions (best practice)

```python
try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(result)
except ValueError:
    print("Please enter a valid number (like 2 or 10).")
except ZeroDivisionError:
    print("Division by zero is not allowed.")
```

Example:

```
Enter a number: 0
Division by zero is not allowed.
```

## else and finally

- `else` runs if no error happened
- `finally` runs no matter what, good for cleanup

```python
try:
    with open("data.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found.")
else:
    print("File read successfully.")
finally:
    print("Done.")
```

## Raise your own error

```python
def check_age(age: int) -> None:
    if age < 0:
        raise ValueError("Age cannot be negative.")
    if age < 18:
        print("Too young.")
    else:
        print("Welcome!")

check_age(25)
```

Expected output:

```
Welcome!
```

## Graph: error handling flow

```mermaid
flowchart TD
  A[Try block] --> B{Error?}
  B -->|No| C[Else block]
  B -->|Yes| D[Except block]
  C --> E[Finally]
  D --> E[Finally]
```

In the next lesson, you will learn modules and imports so your Python code can be organized into multiple files like a real project.
#Python#Intermediate#Error Handling