Exceptions in Python
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.
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 the try statement:
Example
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
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:
Example
This statement will raise an error, because x is not defined:
print(x)
Traceback (most recent call last):
File "demo_try_except_error.py", line 3, in <module>
print(x)
NameError: name 'x' is not defined
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")
Variable x is not defined
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")
Finally
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")
Something went wrong
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:
try:
f = open("[Link]")
try:
[Link]("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
[Link]()
except:
print("Something went wrong when opening the file")
Something went wrong when writing to 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 the raise keyword.
Example
Raise an error and stop the program if x is lower than 0:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
The raise 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:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Traceback (most recent call last):
File "demo_ref_keyword_raise2.py", line 4, in <module>
raise TypeError("Only integers are allowed")
TypeError: Only integers are allowed
Built-in Exceptions
The table below shows built-in exceptions that are usually raised in Python:
Exception Description
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Exception Base class for all exceptions
EOFError Raised when the input() method hits an "end of file"
condition (EOF)
FloatingPointErr Raised when a floating point calculation fails
or
GeneratorExit Raised when a generator is closed (with the close()
method)
ImportError Raised when an imported module does not exist
IndentationErro Raised when indentation is not correct
r
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
KeyboardInterru Raised when the user presses Ctrl+c, Ctrl+z or Delete
pt
LookupError Raised when errors raised cant be found
MemoryError Raised when a program runs out of memory
NameError Raised when a variable does not exist
NotImplemente Raised when an abstract method requires an inherited
dError class to override the method
OSError Raised when a system related operation causes an error
OverflowError Raised when the result of a numeric calculation is too
large
ReferenceError Raised when a weak reference object does not exist
RuntimeError Raised when an error occurs that do not belong to any
specific exceptions
StopIteration Raised when the next() method of an iterator has no
further values
SyntaxError Raised when a syntax error occurs
TabError Raised when indentation consists of tabs or spaces
SystemError Raised when a system error occurs
SystemExit Raised when the [Link]() function is called
TypeError Raised when two different types are combined
UnboundLocalEr Raised when a local variable is referenced before
ror assignment
UnicodeError Raised when a unicode problem occurs
UnicodeEncodeE Raised when a unicode encoding problem occurs
rror
UnicodeDecode Raised when a unicode decoding problem occurs
Error
UnicodeTranslat Raised when a unicode translation problem occurs
eError
ValueError Raised when there is a wrong value in a specified data
type
ZeroDivisionErr Raised when the second operator in a division is zero
or