Python Try Except
Four blocks work together when you deal with errors. try holds the code you want to test for problems, and except deals with the error if one appears.
else runs only when no error happened, while finally runs whatever the outcome of the try and except blocks.
Exception Handling
An error, also called an exception, normally makes Python stop and print an error message.
The try statement lets you catch these exceptions and handle them yourself:
Here the try block fails, so Python moves on to the except block.
Remove the try block and the same error crashes the program:
Example
x has no definition, so the try block ends in an exception:
Output: complete Python program
try:
print(x)
except:
print("An exception occurred")
Example
With no try around it, this line fails because x has no definition:
Output: complete Python program
print(x)
Many Exceptions
A single try can be followed by any number of except blocks, which is handy when one kind of error needs its own special code:
Example
Show one message for a NameError and a different one for anything else:
Output: complete Python program
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
Add the else keyword for code that should run only when the try block raised no errors:
Example
Nothing fails in this try block, so else gets its turn:
Output: complete Python program
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
A finally block, when you include one, always runs, whether or not the try block raised an error.
That makes it a good place for closing objects and cleaning up resources:
The file object does not stay open, and the program is free to carry on.
Example
Output: complete Python program
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Example
Open a file and attempt to write to it, with separate handling for each step. In this run, the file could not even be opened:
Output: complete Python program
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")
Raise an exception
Sometimes your own code should signal a problem when a certain condition is met. The raise keyword does exactly that: it throws (raises) an exception.
You decide both the type of error and the message shown to the user.
Example
Stop the program with an error when x is negative:
Output: complete Python program
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Example
Raise a TypeError unless x is an integer:
Output: complete Python program
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")