When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using the try statement.
1. try block and except block
- The
tryblock lets you test a block of code for errors. - The
exceptblock lets you handle the error.
try:
print(x) # x is not defined
except:
print("An exception occurred")
Because the try block raises an error (since x is not defined), the except block will be executed. Without the try block, the program will crash and raise a NameError.
2. Multiple excepts
You can define as many exception blocks as you want, e.g., if you want to execute a special block of code for a special kind of error.
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
3. else block
You can use the else keyword to define a block of code to be executed if no errors were raised.
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
4. finally block
The finally block, if specified, will be executed regardless if the try block raises an error or not.
This is extremely useful for closing objects and cleaning up resources, like closing a file or a database connection, regardless of whether the operation was successful.
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close() # Always close the file!
except:
print("Something went wrong when opening the file")
5. raise exception
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
You can define what kind of error to raise, and the text to print to the user.
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
6. Custom exceptions
You can create your own exception classes by inheriting from the built-in Exception class. This is useful for building large frameworks where you want to catch specific logic errors.
class ValueTooHighError(Exception):
"""Raised when the input value is too high"""
pass
value = 100
if value > 50:
raise ValueTooHighError(f"Value {value} is greater than limit of 50")
Discussion
Loading comments...