Python Exceptions

Python interpreter stops to execute the program if any error occurs at run-time. These run-time errors are detected during execution is called the exception handling. Handling exception is very important.

Example:

The python variable must be defined earlier in the code before using it. While executing the below code, python interpreter stop the execution throw an error because the variable x is not defined.

print(x)  # variable x is not defined earlier
# Output
NameError: name 'x' is not defined

Exceptions

Python has three built-in methods to handle the exception.

  • try() –  block of code
  • except() – handle the error
  • finally() – It is optional block. It will execute code, regardless of the result of the try- and except blocks.

 

First, Python executes the code of the try block. If any error occurs while execution, python stop to execute the try block and start to execute the except block instead of raising an error. And last, the finally block is executed after finish to the execution of the except block.

try:
  print(x)                              # Raise an error
  print("Hello")
except:
  print("Please define the variable x")
finally:
  print("The 'try except' is finished")
# Output
Please define the variable x
The 'try except' is finished

Here, while executing the program, try block raise an error because the variable is not defined. Hence, except block is executed. The finally block is always executed regardless of the output of the try-except block.

Example – 2

try:
  x = 10
  print("x: ",x)                          # No more error
except:
  print("Please define the variable x")
finally:
  print("The 'try except' is finished")
# Output
x: 10
The 'try except' is finished

Multiple Exceptions

Python also allows you to define multiple exceptions in your program. While the execution of the try block if any error occurs, the only single except block will execute. Let’s see the example of the multiple except block.

try:
    print(x)
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")
finally:
    print("The 'try except' is finished")
# Output
Variable x is not defined
The 'try except' is finished
try:
    print(12/0)                   # error: division by zero
    print(x)
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")
finally:
    print("The 'try except' is finished")
# Output
Something else went wrong
The 'try except' is finished

Python Built-in Exceptions

Python provides various built-in exception class which are listed below.

Exception Class Event
Exception Base class for all exceptions
ArithmeticError Raised when arithmetic computation fails
FloatingPointError Raised when a floating-point computation fails
ZeroDivisionError Raised when a division or modulo by zero
AssertionError Raised when Assert statement fails
OverflowError Raised when the output of an arithmetic computation is too large to be represented
ImportError Raised when the package is not imported
IndexError Raised when the index of a sequence is out of range
KeyboardInterrupt Raised when the user interrupts program execution by pressing the keyboard key
IndentationError Raised when there is incorrect indentation
SyntaxError Raised when syntax error is encountered
KeyError Raised when the given key is not found in the dictionary
NameError Raised when an identifier is not found
TypeError Raised when a function or operation is applied to an object of incorrect type
ValueError Raised when a function gets an incorrect value
IOError Raised when an input/ output computation fails
RuntimeError Raised when a generated error does not fall into any category

 

Example:

try:
   x = [1,2,3]
   print(x[5])

except NameError:
   print("Variable x is not defined")
except ArithmeticError:
   print("Something else went wrong")
except IndexError:
   print("Index is out of range")
# Output
Index is out of range

During execution if any error occurs from out of the defined exception, python interpreter throws an error because it fails to execute any except block. Let’s see the below example. The try block raises an error due to the division by zero, there is no except block exist to catch this error. Hence, the run-time error occurs.

try:
   print(12/0)

except NameError:
   print("Variable x is not defined")
except IndexError:
   print("Index is out of range")
# Output
Traceback (most recent call last):
  File "arg.py", line 2, in <module>
    print(12/0)
ZeroDivisionError: division by zero

It is a good habit to define the base Exception class.

try:
   print(12/0)

except NameError:
   print("Variable x is not defined")
except IndexError:
   print("Index is out of range")
except:
   print("Unkown exception called")

# Output
Unkown exception called

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials