Dremendo Tag Line

Exception Handling in Python Programming

Exceptions in Python

In this lesson, we will understand what is Exception Handling in Python Programming and how to implement it along with some examples.

What is Exception in Python?

An exception is a runtime error that only appears when we run a python program, and the process of eliminating runtime errors from a program is known as Exception Handling.

There are three types of errors that can arise in a python program, and they are:

  • Compile Time Errors or Syntax Errors
  • Logical Errors
  • Runtime Errors
video-poster

Compile Time Errors or Syntax Errors

Compile Time Errors occur when a program fails to compile because of the wrong syntax used in the program statement. The python compiler show this type of error along with the line number and description of the error.

Let's see how a syntax error appeared in a program when we forgot to give a semicolon at the end of a for loop statement.

Example

for i in range(1,6)
    print(i)

Output

Traceback (most recent call last):
  File "D:\example\syntaxerror.py", line 1
    for i in range(1,6)
                      ^
SyntaxError: invalid syntax

Logical Errors

Logical Errors occur when a programmer implements the wrong logic in a program. As a result, the final output of the program becomes wrong. The python compiler and python virtual machine (PVM) can't detect logical errors. It is the programmer's responsibility to figure out and rectify this type of error in a program.

Example

print('Enter 3 numbers')
a=int(input())
b=int(input())
c=int(input())
average = a+b+c/3
print('Average = %.2f' %(average))

Output

Enter 3 numbers
12
31
17
Average = 48.666667

In the above example, the average of the three numbers is 48.666667, which is wrong because there is a logical error in calculating the average. They should be calculated as (a+b+c)/3, giving us the correct average of 20.

Runtime Errors

Runtime Errors occur when the PVM fails to execute the code after compilation. The python compiler can't detect the runtime errors. It is only detected by the PVM while executing the code.

Example 1

print('Enter 2 numbers')
a = int(input())
b = int(input())
c = a/b
print('Result = %f' %(c))

Output

Enter 2 numbers
5
0
Traceback (most recent call last):
  File "D:\example\logicalerror.py", line 4, in 
    c = a/b
ZeroDivisionError: division by zero

In the above example, when we try to divide 5 by 0, the PVM gives a runtime error because 5 can't be divided by 0.

Example 2

x = [12, 36, 72, 37, 81]
print(x[3])
print(x[5])

Output

37
Traceback (most recent call last):
  File "D:\example\pro.py", line 3, in 
    print(x[5])
IndexError: list index out of range

In the above example, when we try to access index 5 in the list, it gives a runtime error because there is no such index available.

List of Built-in Exceptions in Python

Below we have given some of the important lists of built-in exceptions in python that are normally raised in a python program.

Name of Exception Class Description
ArithmeticError This error arises when there is an error in a numeric calculation.
AssertionError This error arises when an assert statement fails.
AttributeError This error arises when an attribute reference or assignment fails.
Exception It is the base class for all exceptions.
EOFError This error arises when the input() method reaches the end of a file condition (EOF).
FloatingPointError This error arises when there is an error in floating point calculation.
GeneratorExit This error arises when a generator's close() method executes.
IOError This error arises when an input or output operation fails.
ImportError This error arises when an imported module does not exist.
IndentationError This error arises when indentation is not specified correctly.
IndexError This error arises when an index does not exist in a sequence.
KeyError This error arises when a key does not exist in a dictionary.
KeyboardInterrupt This error arises when the user hits the Ctrl+C, Ctrl+Z, or Delete keys.
LookupError This error arises when errors raised can't be found.
MemoryError This error arises when there is no memory left for a program to execute.
NameError This error arises when a variable does not exist.
NotImplementedError This error arises when an abstract method is not overridden in an inherited class.
OSError This error arises when a system-related operation causes an error.
OverflowError This error arises when the result of a numeric calculation is too large to be represented.
RuntimeError This error arises when an error does not belong to any specific exceptions.
StopIteration This error arises when an iterator's next() method does not find any further values.
SyntaxError This error arises when a syntax error occurs in a program.
TabError This error arises when indentation consists of tabs or spaces.
SystemError This error arises when a system error occurs.
SystemExit This error arises when the sys.exit() function is executed.
TypeError This error arises when an operation is applied to two inappropriate data types.
UnboundLocalError This error arises when a local variable is referenced before the assignment.
UnicodeError This error arises when a problem occurs related to Unicode.
UnicodeEncodeError This error arises when a problem occurs during Unicode encoding.
UnicodeDecodeError This error arises when a problem occurs during Unicode decoding.
UnicodeTranslateError This error arises when a problem occurs during Unicode translation.
ValueError This error arises when a wrong type value is received in a data type that does not support it.
ZeroDivisionError This error arises when a number is divided by 0.

Exception Handling

We can handle exceptions in a python program using the following blocks.

  • try block
  • except block
  • else block
  • finally block

try block

In the try block, the programmer will write such statements that may cause exceptions in the program.

Syntax of try block

try:
    statement
    statement
    ...
    ...
    ...

except block

The programmer writes the except block, including the exception name to be handled in this block. Here programmer will display a detailed message to the user regarding the exception that has occurred in the program.

Syntax of except block

except exceptionname:
    message statement
    ...
    ...
    ...

else block

The else block is an optional block where the programmer writes statements that execute if there is no exception in the try block.

Syntax of else block

else:
    statement
    statement
    ...
    ...
    ...

finally block

The finally block is also an optional block where the programmer writes statements that are executed irrespective of whether an exception has occurred in the try block or not.

Syntax of finally block

finally:
    statement
    statement
    ...
    ...
    ...

Let's handle the exception when a number is divided by 0.

Example

try:
    print('Enter 2 numbers')
    a = int(input())
    b = int(input())
    c = a/b
    print('Result = %f' %(c))

except ZeroDivisionError:
    print('A number can not be divide by 0')

Output

Enter 2 numbers
5
0
A number can not be divide by 0

To print only the default message of an exception, we have to define the exception name with a new name using the keyword as. After that, we can use the alias name to print the default message of the exception. See the example given below.

Example

try:
    print('Enter 2 numbers')
    a = int(input())
    b = int(input())
    c = a/b
    print('Result = %f' %(c))

except ZeroDivisionError as ex:
    print(ex)

Output

Enter 2 numbers
24
0
division by zero

In the above program, we have defined ex as the new name of the exception ZeroDivisionError.

Let's see an example of handling multiple exceptions using the multiple except blocks.

Example

try:
    print('Enter 2 numbers')
    a = int(input())
    b = int(input())
    c = a/b
    print('Result = %f' %(c))

    data = [12, 84, 36, 91, 57]
    print(data)
    print('Enter index to print the value from the above list')
    i = int(input())
    print('The value at index %d = %d' %(i,data[i]))

except ZeroDivisionError:
    print('A number can not be divide by 0 Try again')

except IndexError:
    print('The index your are looking for does not exist in the list')

Output

Enter 2 numbers
5
2
Result = 2.500000
[12, 84, 36, 91, 57]
Enter index to print the value from the above list
6
The index your are looking for does not exist in the list

In the above example, we have implemented two except blocks to handle two different types of exceptions that may occur within the try block.

Let's see how to implement else block along with try and except blocks.

Example

try:
    data = [12, 84, 36, 91, 57]
    print(data)
    print('Enter index to print the value from the above list')
    i = int(input())
    print('The value at index %d = %d' %(i,data[i]))

except IndexError:
    print('The index your are looking for does not exist in the list')

else:
    print('Program executed successfully')

Output

[12, 84, 36, 91, 57]
Enter index to print the value from the above list
2
The value at index 2 = 36
Program executed successfully

In the above program, if no exception arises in the try block, then the codes written in the else block will execute.

Let's see one more example of how to implement else and finally block along with try and except blocks.

Example

try:
    print('Enter 2 numbers')
    a = int(input())
    b = int(input())
    c = a/b
    print('Result = %f' %(c))

except ZeroDivisionError:
    print('A number can not be divide by 0 Try again')

else:
    print('No exception arises')

finally:
    print('Program ends')

Output

Enter 2 numbers
5
0
A number can not be divide by 0 Try again
Program ends

Enter 2 numbers
5
2
Result = 2.500000
No exception arises
Program ends

If an exception arises in the try block, then the except and finally, blocks will execute. If no exception arises in the try block, then both else and finally block will execute. See the output of the above program.

Raise an Exception in Python

We can manually raise an exception in python program using the raise keyword.

Example

print('Enter a number between 1 to 7')
n = int(input())
if n<1 or n>7:
    raise Exception('Invalid Input')

Output

Enter a number between 1 to 7
0
Traceback (most recent call last):
  File "D:\example\raiseexception.py", line 4, in 
    raise Exception('Invalid Input')
Exception: Invalid Input

User-Defined Exceptions

Sometimes a programmer may want a specific type of exception which is not available in the built-in exceptions list. In that case, the programmer can create a new user-defined exception class by inheriting the Exception class in it.

Example

class RangeError(Exception):
    def __init__(self, msg):
        super().__init__(msg)

print('Enter a number in range 1 to 5')
n = int(input())

if n<1 or n>5:
    raise RangeError('Number not in range')

Output

Enter a number in range 1 to 5
8
Traceback (most recent call last):
  File "D:\example\customerror.py", line 9, in 
    raise RangeError('Number not in range')
RangeError: Number not in range

In the above example, we have created a new custom error class named RangeError by inheriting the Exception class. After that, inside the sub-class (RangeError) constructor, using the super() function, we initialized the base class (Exception) constructor with the msg argument.

At last, we have used the raise keyword to raise errors using our user-defined exception class RangeError.