Python - Try Except

When Python interpreter executes a program and encounters an error or exception, it usually stops and throws error message. Handling such situation is termed as error handling or exception handling and Python has three keywords for this purpose:

• try: It is used to test a block of statements for error.
• except: It has a block of statements which executes when error occurs and handles error.
• finally: It has a block of statements which executes regardless of try-except blocks result.

try-except blocks

In the below example, x is not defined anywhere in the program, which raises an error. As the error occurred in try block of statement, it will be handled by its except block of statement. Without try block, the program will stop immediately after an error and throw error message.

Syntax

try:
statements
except:
statements


Example:

try:
x = x + 1
print(x)
except:
print("An error occurred.")


Output

An error occurred.


Many except blocks

A program can have multiple except blocks to handle each type of exception differently.

Syntax

try:
statements
except errortype_1:
statements
except errortype_2:
statements
...
...
except:
statements


Example:

try:
x = 1
y = 0
x = x / y
print(x)
except ZeroDivisionError:
print("Zero Division Error")
except (ValueError, TypeError):
print("Value/Type Error")
except:
print("An error occurred.")


Output

Zero Division Error


except block with else

else block statement can also be added with try-except blocks which is executed when no error has occurred.

Syntax

try:
statements
except:
statements
else:
statements


Example:

try:
x = 10
y = 2
x = x / y
print(x)
except ZeroDivisionError:
print("Zero Division Error")
except:
print("An error occurred.")
else:
print("No error has occurred.")


Output

5.0
No error has occurred.


finally block

In the below example, finally block of statement is executed regardless of try-except block results, which facilitates the program to close the file before proceeding further.

Syntax

try:
statements
except:
statements
else:
statements
finally:
statements


Example:

MyFile = None
try:
MyFile = open("math_example.txt")
x = x/y
print(x)
except:
print("An error occurred.")
finally:
if MyFile == None:
print("MyFile does not exist.")
else:
print("MyFile has been closed.")
MyFile.close()


Output

An error occurred.
MyFile does not exist.

Exception Name & Description
Exception NameDescription
AssertionError Raised when the assert statement fails.
AttributeError Raised on the attribute assignment or reference fails.
EOFError Raised when the input() function hits the end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raised when a generator's close() method is called.
IndexError Raised when the index of a sequence is out of range.
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in the local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when a system operation causes a system-related error.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by the next() function to indicate that there is no further item to be returned by the iterator.
SyntaxError Raised by the parser when a syntax error is encountered.
IndentationError Raised when there is an incorrect indentation.
TabError Raised when the indentation consists of inconsistent tabs and spaces.
SystemError Raised when the interpreter detects internal error.
SystemExit Raised by the sys.exit() function.
TypeError Raised when a function or operation is applied to an object of an incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translation.
ValueError Raised when a function gets an argument of correct type but improper value.
ZeroDivisionError Raised when the second operand of a division or module operation is zero.