Python Try/Except & Error Handling
Prevent your Python scripts from crashing. Learn try, except, finally blocks and how to raise custom exceptions properly.
Overview
Errors are a fact of life in programming. Python allows you to handle unexpected errors gracefully without crashing the whole program.
The "try" block lets you test a block of code for errors. The "except" block lets you handle the error.
The "finally" block lets you execute code, regardless of the result of the try- and except blocks. Using try blocks prevents catastrophic app failures.
Code Example
Creating structural safety when interacting with potentially dangerous or non-existent file structures.
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Error: Cannot divide by zero!"
except TypeError:
return "Error: Both arguments must be numbers."
else:
return f"The result is {result}"
finally:
print("Execution completed.")
print(divide_numbers(10, 2))
print(divide_numbers(10, 0))Execution completed.
The result is 5.0
Execution completed.
Error: Cannot divide by zero!Real-world Use Cases
- Validating user form submissions
- Ensuring network requests do not crash on timeout
- Closing database connections securely in a finally block
Frequently Asked Questions
What is the "raise" keyword?
The raise keyword is used to raise an exception purposefully. You can define what kind of error to raise, and the text to print to the user.