Python Error Handling
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
Basic Try-Except
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
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")
Finally
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()
except:
print("Something went wrong when opening the file")
Raising Exceptions
As a Python developer you can choose to throw an exception if a condition occurs.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Custom Exceptions
You can define your own exceptions by creating a new class that is derived from the built-in Exception class.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e)