Python Try Except
Python Try Except
The try block lets you test a block of code for errors.
The finally 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.
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Try it Yourself »
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:
Example
This statement will raise an error, because x is not defined:
print(x)
Try it Yourself »
https://www.w3schools.com/python/python_try_except.asp 1/4
7/15/2021 Python Try Except
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 a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Try it Yourself »
Else
You can use the else keyword to define a block of code to be executed if no errors were raised:
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Try it Yourself »
Finally
https://www.w3schools.com/python/python_try_except.asp 2/4
7/15/2021 Python Try Except
The finally block, if specified, will be executed regardless if the try block raises an error or
not.
Example
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Try it Yourself »
Example
Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
Try it Yourself »
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.
Example
https://www.w3schools.com/python/python_try_except.asp 3/4
7/15/2021 Python Try Except
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Try it Yourself »
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:
x = "hello"
Try it Yourself »
https://www.w3schools.com/python/python_try_except.asp 4/4