Error handling in Python is an essential skill that separates beginner programmers from professionals. In this complete guide, you will learn how to use try except to catch, handle, and prevent exceptions, creating robust and reliable applications.
The try/except block in Python is the main structure for exception handling. It allows your program to detect errors during execution and respond in a controlled manner, preventing the application from crashing completely.
Exceptions are errors detected during execution. Unlike syntax errors (which prevent code from running), exceptions occur while the program is running. You can learn more in the official Python documentation.
## Basic try/except example
try:
number = int(input("Enter a number: "))
print(f"You entered: {number}")
except ValueError:
print("❌ Error: Please enter numbers only!")
number = 0
Full Structure: Try/Except/Else/Finally
Python offers four main blocks for handling exceptions:
- try: Contains the code that may generate an exception.
- except: Executes when an exception occurs.
- else: Executes when no exception occurs.
- finally: Always executes, regardless of errors (ideal for cleanup).
Common Exception Types
Knowing common exception types is fundamental for effective handling:
ValueError: Incorrect value for an operation (e.g.,int("abc")).TypeError: Operation with an incorrect type (e.g.,"2" + 2).IndexError: Index out of range in lists.KeyError: Key does not exist in dictionaries.ZeroDivisionError: Division by zero.
Use else, finally, and Exception Chaining
Keep the try block as small as possible so it catches only the operation that may fail. Put code that should run after a successful attempt in else, and reserve finally for cleanup that must happen in every outcome. Context managers usually provide a clearer way to close files and connections.
def load_port(value: str) -> int:
try:
port = int(value)
except ValueError as error:
raise ValueError("Port must be an integer") from error
else:
if not 1 <= port <= 65535:
raise ValueError("Port out of range")
return port
Production Error-Handling Checklist
- Catch the most specific exception you can handle.
- Do not silence failures with a bare
except. - Preserve the original cause with
raise ... from error. - Log unexpected failures with context, but never expose secrets.
- Create domain exceptions when callers need to distinguish business failures.
Tests should cover the successful path and each expected failure. An exception message should explain what failed and which input or operation caused it, while avoiding passwords, tokens, and personal data.
Conclusion
Error handling is fundamental for creating robust and professional applications. Master try/except, and your programs will be ready for production! For more, check our guides on Functions and OOP to see how to use exceptions in complex systems.