11. Error Handling with try/except
Level: IntermediateDuration: 24m
Why Handle Errors?
Errors happen—network issues, wrong user input, missing files. Without error handling, your program will crash. With try/except, you can catch errors and respond gracefully instead of crashing.
Basic try/except
python
try:
number = int(input("Enter a number: "))
print(10 / number)
except:
print("Something went wrong!")💡 Avoid using a bare `except:` — it catches all errors and makes debugging harder. Be specific when possible.
Catching Specific Errors
Python errors have names like ValueError, FileNotFoundError, ZeroDivisionError, etc. You can handle them individually.
python
try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("You can't divide by zero!")Using else and finally
`else` runs only if no error occurs. `finally` runs no matter what—perfect for cleanup actions.
python
try:
result = 10 / 2
except ZeroDivisionError:
print("Math error")
else:
print("Success! Result is", result)
finally:
print("This always runs.")Raising Your Own Errors
Use `raise` to trigger errors intentionally when something is wrong.
python
def withdraw(amount):
if amount <= 0:
raise ValueError("Amount must be greater than zero")
print(f"Withdrew ${amount}")
withdraw(-50)Common Exception Types
| Exception | When It Happens |
|---|---|
| ValueError | Wrong value type entered |
| TypeError | Wrong data type used |
| ZeroDivisionError | Dividing by zero |
| FileNotFoundError | File path incorrect or missing |
| IndexError | List index out of range |
| KeyError | Missing dictionary key |
All Built-in Python Exceptions
Mini Project Step
Add error handling to your calculator program. Catch invalid numbers and division by zero using try/except, and show a friendly message instead of crashing.