Raise and Finally¶
The finally Block¶
The finally block, if specified, will be executed regardless if the try block raises an error or not.
try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
print("File closed successfully.")
except:
print("Something went wrong when opening the file")
This is extremely useful for closing resources (like files or database connections).
Raising an 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.
Raising Specific Types¶
You can define what kind of error to raise, and the text to print to the user.
Custom Exceptions
You can even create your own exception classes by inheriting from the built-in Exception class!