PythonTry Except
Thetry block lets you test a block of code for errors.
Theexcept block lets you handle the error.
Theelse block lets you execute code when there is no error.
Thefinally block lets you execute code, regardless of the result of the try- and except blocks.
Exception Handling
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 thetry statement:
Example
Thetry block will generate an exception, becausex is not defined:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Many Exceptions
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:
Example
Print one message if the try block raises aNameError and another for other errors:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
See more Error types in ourPython Built-in Exceptions Reference.
Else
You can use theelse keyword to define a block of code to be executed if no errors were raised:
Example
In this example, thetry block does not generate any error:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
Thefinally block, if specified, will be executed regardless if the try block raises an error or not.
Example
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
This can be useful to close objects and clean up resources:
Example
Try to open and write to a file that is not writable:
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")
The program can continue, without leaving the file object open.
Raise an exception
As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use theraise keyword.
Example
Raise an error and stop the program if x is lower than 0:
if x < 0:
raise Exception("Sorry, no numbers below zero")
Theraise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
Example
Raise a TypeError if x is not an integer:
if not type(x) is int:
raise TypeError("Only integers are allowed")

