# Exceptions and File Handling in Python — try/except and open()

Source: https://skills101.in/learn/python/python-exceptions-and-files — Skills101 free tutorial (Python Programming). Updated 2026-11-09.

Real programs face bad input, missing files and network problems. Instead of crashing, a good program **handles** these errors. This lesson also covers reading and writing files, where errors are common.

## Part A — Exceptions

![Flow: the try block runs; if no error, else runs; if an error happens, except runs; finally always runs at the end](https://skills101.in/learn-img/python/try-except.svg)

```python
def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    else:
        return result
    finally:
        print("checked", a, b)

print(safe_divide(10, 2))
print(safe_divide(5, 0))
```

```text
checked 10 2
5.0
checked 5 0
Cannot divide by zero
```

- `try` — the code that might fail
- `except SomeError` — runs if that error happens
- `else` — runs if **no** error happened
- `finally` — **always** runs (good for cleanup)

### Common exceptions

| Exception | When |
|---|---|
| `ValueError` | right type, wrong value: `int("abc")` |
| `TypeError` | wrong type: `"5" + 5` |
| `ZeroDivisionError` | dividing by zero |
| `IndexError` | list index out of range |
| `KeyError` | missing dictionary key |
| `FileNotFoundError` | file doesn't exist |

### Handling bad input

```python
# Input: abc
# Input: 21
while True:
    try:
        age = int(input())
        break
    except ValueError:
        print("Please enter a number")
print("Age:", age)
```

```text
Please enter a number
Age: 21
```

### Raising your own errors

```python
def set_marks(m):
    if not 0 <= m <= 100:
        raise ValueError("marks must be between 0 and 100")
    return m

try:
    set_marks(120)
except ValueError as e:
    print("Error:", e)
```

```text
Error: marks must be between 0 and 100
```

> Catch **specific** exceptions. A bare `except:` hides real bugs.

## Part B — Files

Always open files with **`with`** — it closes the file automatically, even if an error happens.

| Mode | Meaning |
|---|---|
| `"r"` | read (default); error if missing |
| `"w"` | write; **erases** the file first |
| `"a"` | append to the end |

### Write and read a text file

```python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Learn Python\n")
    f.write("Practise daily\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())
```

```text
Learn Python
Practise daily
```

### CSV files

```python
import csv

rows = [["name", "marks"], ["Asha", 92], ["Ravi", 74]]
with open("marks.csv", "w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows(rows)

with open("marks.csv", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], int(row["marks"]) + 5)
```

```text
Asha 97
Ravi 79
```

### JSON files

```python
import json

data = {"name": "Asha", "skills": ["python", "sql"]}
with open("profile.json", "w", encoding="utf-8") as f:
    json.dump(data, f)

with open("profile.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded["skills"][1])
```

```text
sql
```

## Common mistakes

- Opening with `"w"` when you meant `"a"` — it wipes the file.
- Forgetting `encoding="utf-8"` and getting errors with ₹ or Hindi text on Windows.
- Catching every exception with a bare `except:`.

## Quick recap

- try / except / else / finally; catch specific exceptions; `raise` your own.
- `with open(path, mode, encoding="utf-8") as f:` — always.
- "r" read, "w" overwrite, "a" append.
- `csv` and `json` modules handle structured files.


Practice quiz and free certificate: https://skills101.in/learn/python/python-exceptions-and-files