This is the 17th in a series of Python tutorials; for more, check out my Python collection!
When we write code, we may encounter a variety of error conditions, such as division by zero, file not found, network problems, and so on. To handle these problems gracefully, Python provides exception handling mechanisms.
1 Basic structure of exception handling
Exception handling in Python relies heavily on thetry
cap (a poem)except
Statements. The basic structure is as follows:
try.
# Code block to try to execute
some_code()
except SomeException as e.
# If an exception of the specified type is thrown in the try block, execute this code block
print(f "An error occurred: {e}")
2 Components of Exception Handling
-
try block: This section contains the code you wish to monitor that may raise an exception.
-
except blocks: If an exception is thrown in a try block, the execution jumps to an except block.
- You can specify a specific type of exception to catch, or you can catch all exceptions without specifying a type.
- If an exception type is specified, you can also get an exception object to handle.
-
else block(Optional): If no exception occurs, the code in the else block is executed.
-
finally block(Optional): The code in the finally block is executed regardless of whether or not an exception occurs, and is typically used to free up resources, such as closing files or cleanup operations.
2.1 Examples
Here is a simple example of exception handling:
try.
# Trying to open a non-existing file here will throw a FileNotFoundError
with open("", "r") as file: content = ()
content = ()
print(content)
except FileNotFoundError as fnf_error:
# Handle FileNotFoundError exceptions.
print(f "File not found: fnf_error}")
else: # Handle FileNotFoundError exception.
# If no exception is thrown, print the contents of the file
print("File was read")
finally.
# Execute here with or without an exception.
print("Printed with or without exception.")
3 Multiple except blocks
You can have more than oneexcept
block to handle different types of exceptions separately:
try:
# May raise many types of exceptions
x = 1 / 0 # ZeroDivisionError
y = "hello" + 5 # TypeError
except ZeroDivisionError as zde:
print(f"Cannot divide by zero: {zde}")
except TypeError as te:
print(f"Type error occurred: {te}")
4 Customized exceptions
Custom exceptions are usually implemented by inheriting from one of Python's built-in exception classes, such as Exception or a more specific exception class. Throwing exceptions is implemented with the raise keyword.
You can also define your own exception classes and then throw them in your code:
class CustomError(Exception):
pass
class MyError(CustomError):
pass
try:
raise MyError("This is a custom error message.")
except MyError as e:
print(f"Capture CustomizationMyErrorexceptions:{e}")
except CustomError as e:
print(f"Capture CustomizationCustomErrorexceptions:{e}")
Note that the order of catching exceptions is from top to bottom, when executing line 8, determine whether the exception thrown is a MyError exception or its subclasses, if it is valid, then execute line 9, followed by lines 10 and 11 are no longer executed.
What if the order of the two exception catching codes were reversed? As follows:
class CustomError(Exception):
pass
class MyError(CustomError):
pass
try:
raise MyError("This is a custom error message.")
except CustomError as e:
print(f"Capture CustomizationCustomErrorexceptions:{e}")
except MyError as e:
print(f"Capture CustomizationMyErrorexceptions:{e}")
The result is also that line 9 is executed and the following lines 10 and 11 are not executed. Although the following MyError is more precise, the code executes to line 8 to determine that the exception is CustomError or its subclasses hold, so line 9 is executed.
4.1 Default Exception Messages
When raise exceptions do not specify an exception message, a default message can be defined
class MyError(Exception).
def __init__(self, message="Default message when thrown message is null").
super(). __init__(message)
pass
try: raise MyError()
__init__(message) pass try: raise MyError()
except MyError as e.
print(f "Caught custom MyError exception: {e}")
try: raise MyError()
raise MyError("Error report blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah")
except MyError as e.
print(f "Caught custom MyError exception: {e}")
printable
Catching custom MyError exceptions: default message when thrown message is empty
Catching custom MyError exceptions: reporting errors la la la la la la la la