Exception Handling
Exception Handling
1
try-except-finally
Handling errors in code where an exception might occur, but you want to continue execution.
Handles exceptions gracefully, keeps the program running after catching error.
Ensures resources are freed, files are closed, and cleanup actions are taken.
Can hide bugs if used excessively or incorrectly.
It can make code less readable if not used carefully.
2
Raising Exceptions (raise)
Explicitly raise exceptions when a condition is not met, for better control over error handling.
Customizable error handling, useful for catching specific exceptions in context.
Improves code clarity when handling specific conditions.
Overuse may lead to excessive custom exceptions that clutter the code.
Can make code harder to follow if exceptions are raised frequently.
3
Custom Exceptions
Create custom exceptions to better represent specific errors in your program.
Allows for more descriptive error messages and clearer error handling.
Can complicate code unnecessarily if simple exceptions suffice.
Useful for domain-specific errors that built-in exceptions don't cover.
Makes debugging and error handling more intuitive.
Overuse can lead to excessive custom exception classes.
4
Assertions
Verifying conditions during development to catch bugs early by ensuring a condition is true.
Helps catch bugs early, useful during development.
May cause performance issues if assertions are used excessively in production.
Ensures that certain conditions hold true, which can prevent logical errors.
Improves code quality by validating conditions before proceeding.
Can be disabled globally with the -O
flag, rendering them useless in production.
5
try-except with Multiple Exceptions
Catch multiple different types of exceptions in a single block.
Can catch multiple exceptions in one place, providing cleaner error handling.
If not careful, may catch unrelated exceptions, leading to difficult debugging.
Code examples
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Finally block executed")
Last updated