How to Handle Exceptions in Python: A Practical Guide
Errors happen in every Python program. Instead of letting your script crash, you can catch and manage exceptions gracefully. Python’s try-except block is your main tool—it lets you define a fallback action when something goes wrong. This tutorial covers the essentials: catching specific errors, using else and finally, and raising your own exceptions.
The core pattern is straightforward: place risky code inside a try block, then handle the error in an except block. For example, reading a user’s input as an integer might raise a ValueError. By catching that, you can prompt again instead of crashing.
1. Catching Specific Exceptions
Always catch the exact exception type you expect. Catching all exceptions with a bare except: is bad practice—it hides bugs. Instead, target ValueError, FileNotFoundError, KeyError, etc. Use multiple except blocks for different cases.
- Example:
try: x = int(input()) except ValueError: print("Not a number") - You can also capture the exception object:
except ValueError as e: print(e)
2. Adding Else and Finally
else runs only if no exception occurred—great for code that must not execute after an error. finally always runs, even if the try block raises an exception. It’s perfect for cleanup actions like closing files or releasing resources.
- Else:
try: ... except ...: ... else: print("Success") - Finally:
finally: file.close()
3. Raising Your Own Exceptions
Use raise to signal when conditions aren’t met. You can raise built-in exceptions or create custom ones by subclassing Exception.
raise ValueError("Invalid age")- Custom:
class MyError(Exception): passthenraise MyError("Custom")
4. Best Practices
- Don’t suppress exceptions you don’t understand. Log the error or re-raise.
- Keep
tryblocks minimal—only wrap code that might fail. - Avoid catching
Exceptionunless you have a very specific reason.
Mastering exception handling makes your Python programs robust and user-friendly. Start by catching specific errors, then gradually add else and finally to control the flow. Your code will thank you.