Python Exceptions Handling (With Examples)

In this Python tutorial, we will learn Python Exceptions Handling and also we will cover these topics:

  • What is an Exception?
  • Types of error in Python
  • Python Syntax Error
  • Python Exceptions Handling Examples
  • Example on try
  • Examples of except
  • Example on try, except and else
  • Example of try-finally
  • Exception handling keyword
  • Raise an exception
  • Raise an error
  • Raise valueError
  • Example on KeyError
  • Example on KeyboardInterrupt Error
  • Example on OverflowError
  • Example on IndexError
  • Example on NameError
  • Example on ImportError
  • Example on AssertionError
  • Example on AttiributeError

What is an Exception?

An Exception is an error that occurred during the execution of a piece of code. A runtime error is called an Exception, the cause of the exception is improper input.

Types of error in Python

AsserationErrorIt occurs when an assert statement fails
AttributeErrorIt occurs when attribute assignment fails
FloatingPointErrorIt occurs when the floating-point operation fails
MemoryErrorIt occurs when the operation is out of memory
IndexErrorIt occurs when the order is out of range
NotImplementedErrorIt occurs because of abstract methods
NameErrorWhen the variable is not found in the local or global scope
KeyErrorIt occurs when the key is found in the dictionary
ImportErrorIt occurs when the imported module is not present
ZeroDivisorErrorIt occurs when the second operand is 0
GeneratorExitIt occurs when the generator’s close() is
OverFlowErrorIt occurs when the result of an arithmetic operation is too large
IndentationErrorIt occurs when the indentation is not correct
EOFErrorIt occurs when the input() function end in the file condition
SyntaxErrorIt occurs when a syntax error is raised
TabErrorIt occurs when inconsistent space or tabs
ValueErrorIt occurs when the function gets a correct argument and an incorrect value
TypeErrorIt occurs when the function or operation is incorrect
SystemErrorIt occurs when the interpreter detects an internal error
Types of errors in Python
  • When error occurs exception is called, python will stop it and generates error message.

The exception is handled by try, except and finally.

  • try – It checks the error in the block of code
  • except – It handles the error
  • finally – It executes the code.

Python Syntax Error

Now, we can see syntax error in Python.

  • In this example, I have used try to check the error in the block as the error is present in the syntax of print(hello).
  • The except is used as except SyntaxError as e. The except is executed.

Example:

try:
  print(hello)
except SyntaxError as e:
  print("Invalid syntax")
except:
    print("Invalid syntax")

As the except is executed, we can see the output as “Invalid syntax”. You can refer to the below screenshot for the output.

Python Syntax Error
Python Syntax Error

Python Exceptions Handling Examples

Now, let us see various examples of Python exceptions handing.

Example on try in Python

Now, we can check an example using try in python.

In this example, I have used try to check the error in the block as the error is present in the print(a+b). The except is executed.

Example:

try:
  print(a+b)
except:
  print("exception occured")

We can see the output as exception occured in the below screenshot.

Example on try
Example on try

Examples of except in Python

Here, we can check the example using except in Python.

  • In this example, I have used try to check the error in the block as the error is present in print(x) because x is not defined here.
  • The except is used as except TypeError, the except is executed. So, the except: print(“Error”) is executed.

Example:

try:
  print(x)
except TypeError:
  print("x is not defined")
except:
  print("Error")

As the except is executed, we can see the output as “Error”. The Below screenshot shows the output:

Examples of except
Examples of except

Example on try, except and else in Python

Here, we can see the examples on try, except and else in Python.

  • In this example, I have opened the file in the try block to check if the file contains an error or the file is not found.
  • The except IOError is used after the except the else statement is used if the file is not present and content is not written in that, then else will execute.

Example:

try:
   file = open("sushma.txt", "w")
   file.write("This is the test file")
except IOError:
   print("No file found")
else:
   print("The content is not written in the file")
   file.close()

We can see the else is executed as “The content is not written in the file” as the output. You can refer to the below screenshot for the output.

Example on try except and else 1
Example on try, except and else

Example of try-finally in Python

Here, we can see the example of try finally in Python.

  • In this example, I have used try to check the error in the block as the error is present in print(x) because x is not defined here.
  • As the finally block is present, the finally is executed. Whether the exception occurs or not always the finally is executed, if we use the finally block.
  • Even the except block also get printed along with finally.

Example:

try:
  print(x)
except:
  print("x is not defined")
finally:
  print(" The finally is executed")

The Below screenshot shows the output:

Python try finally
Python try finally

Exception handling keyword

Python uses try and except keywords to handle the exception.

Raise an exception in Python

  • The raise keyword is used to raise an exception.
  • The name of the exception class is required to raise an exception.
  • Built-in errors are raised implicitly and built-in exceptions can be forced.

In this example, I have taken a number = 2 and if condition is used and raise ValueError is written along with the error message.

Example:

number = 2
if number < 36:
    raise ValueError('The given number is less than 36')

The below screenshot shows the output as valueError along with the error message.

Raise an exception in Python
Raise an exception in Python

Raise an error in Python

Now, we can see how to raise an error in python.

  • In this example, I have taken a variable as num and assigned a char as”hello”.
  • The if condition is used as if not type(x) is int if the condition is not true error is raised.

Example:

num = "python"
if not type(num) is int:
  raise TypeError("Only integers are allowed")

As the condition is not true, we can see a TypeError as the output. You can refer to the below screenshot.

Python Exceptions Handling
Raise an error in Python

Raise valueError in Python

Now, we can see how to raise ValueError in python.

  • In this example, I have taken a variable as the number and assigned number = 5, and if condition is used as if number < 19.
  • As the assigned number is less than 19 the value error is raised by using raise ValueError(‘number should not be less than 19’).

Example:

number = 5
if number < 19:
    raise ValueError('number should not be less than 19')

You can see the error as the output in the below screenshot.

Raise valueError in Python
Raise valueError in Python

Example on KeyError in Python

Now, we can see example on KeyError in python.

  • In this example, I have taken a dictionary as Rate and assigned key and value pair and to enter the value the input statement is used.
  • The try block is used to check if any error occurs in a dictionary and to execute even if the error is found the except KeyError is used.

Example:

Rate = { 'bottle' : 5, 'chair' : 1200, 'pen' : 50}
item = input('Enter the item: ')
try:
   print(f'The rate of {item} is {Rate[item]}')
except KeyError:
    print(f'The price of {item} is not found')

As the item car is not there in the dictionary, we can see the output as the price of the car is not found in the below screenshot.

Example on KeyError in Python
Example on KeyError in Python

Example on KeyboardInterrupt Error in Python

Here, we can see the example on KeyboardInterrupt Error in python.

  • In this example, I have used try block to check the error. Here I have used inp = input(“Enter the input:”) to get the input.
  • If the user enters any word exception does not occur if the user enters ctrl+c except is executed.

Example:

try:
    inp = input("Enter the input:")
    print ('Press Ctrl+c')
except KeyboardInterrupt:
    print ('Caught KeyboardInterrupt')
else:
    print ('No exception occurred')

We can see the two outputs one by giving the input as a book then the output is No exception occurred and when the input is ‘ctrl+c’ the output will be ‘Caught KeyboardInterrupt’.You can refer to the below screenshot for the output.

Example on KeyboardInterrupt Error in Python
Example on KeyboardInterrupt Error in Python

Example on OverflowError in Python

Now, we can check the example on OverflowError in python.

  • In this example, I have taken a variable as i and assigned i=1 and used try block to check the error, I have taken a variable as num = 2.5**i multiplication operation is performed.
  • The for loop is used for iteration and range is given when the result of the multiplication is more than the given range the OverflowError occurs, as the error is present the except is executed.

Example:

i=1
try:
  num = 2.5**i
  for i in range(20):
      print(i, num)
      num = num**8 
except OverflowError as e:
          print('Overflowed after ', num, e)

As the except is executed, we can see the output as overflowed after the given range. You can refer to the below screenshot for the output.

Example on OverflowError in Python
Example on OverflowError in Python

Python IndexError Example

Now, we can see example on IndexError in python.

  • In this example, I have used try block to check the error. Here I have taken a list and assigned list = [1,2,3,5,6,7].
  • To print the value from the list I have used print(list[8]), The 8 is the index value.
  • As the list contain the value up to range 5 but the value is 8 the error occurs.
  • So, the except is used as except IndexError as e and except is executed.

Example:

try:
    list = [1,2,3,5,6,7]
    print(list[8])
except IndexError as e:
    print(e)
print("index error")

As the except is executed, we can see the output as Index error. You can refer to the below screenshot for the output:

Example on IndexError in Python
Example on IndexError in Python

Python NameError Example

Here, we can see the example on NameError in python.

  • In this example, I have used try to the error in the block of the code to print the word cat as there is an error in print(cat).
  • The except is assigned as except NameError, the except is executed.

Example:

try:
    print(cat)
except NameError:  
    print ("NameError:'cat' is not defined")
else:  
    print ("word found no error")

As the error is found except is executed as NameError:’cat’ is not defined as the output. The below screenshot shows the output

Example on NameError in Python
Example on NameError in Python

Python ImportError Example

Now, we can see the example on ImportError in python.

  • In this example, I have imported a module called sys, and a try block is used to check the error.
  • I have imported a module called math from cv as the error is there in the module. So, except is used as except Exception.

Example:

import sys
try:
    from cv import math
except Exception:
    print("improper module")

As there is an error while importing, except is executed and we can see an improper module as the output. You can refer to the below screenshot for the output.

Example on ImportError in Python
Example on ImportError in Python

Example on AssertionError in Python

Here, we can see the example on AssertionError in python.

  • In this example, I have used try block to check the error in the block and a=5 and b=5
  • As the condition is given as assert a != b, as the condition is not true. AssertionError occurs the except is given as except AssertionError. Otherwise, the else condition is executed..

Example:

try:  
    a = 5
    b = 5
    assert a != b
except AssertionError:  
        print ("Exception Error")
else:  
    print ("Success, no error!")

As the exception is occured we can see the output as “Exception Error”. You can refer to the below screenshot.

Example on AssertionError in Python
Example on AssertionError in Python

Example on AttiributeError in Python

Now, we can see the example on AttiributeError in python.

  • In this example, I have taken a class as class Attributes and passed the parameter object, the variable is declared as num = 5.
  • I have used try block to check the error in the block of the code the except is used as except AttributeError as the error is present except is executed.

Example:

class Attributes(object):
    num = 5
    print(num)
try:
    object = Attributes()
    print (object.attribute)
except AttributeError:
    print ("Attribute Exception")

As the except is executed, we can see the output as “Attribute Exception” in the below screenshot.

Example on AttiributeError in Python
Example on AttiributeError in Python

You may like the following Python tutorials:

In this tutorial, we have learned about Python Exceptions Handling, and also we have covered these topics:

  • What is an Exception?
  • Types of error
  • Python Syntax Error
  • Python Exceptions Handling Examples
  • Example on try
  • Examples of except
  • Example on try, except and else
  • Example of try-finally
  • Exception handling keyword
  • Raise an exception
  • Raise an error
  • Raise valueError
  • Example on KeyError
  • Example on KeyboardInterrupt Error
  • Example on OverflowError
  • Example on IndexError
  • Example on NameError
  • Example on ImportError
  • Example on AssertionError
  • Example on AttiributeError