Python Catching Specific Exception


Exception superclass

Exception is the superclass of all the classes available in exception handling. So in the except block, we can use superclass exception or its sub-classes to get the knowledge of the exception that occurred. In the except block we can handle any number of exceptions.

Using Exception superclass.

In [1]:
try:
    a = 1
    b = 0
    a/b
except Exception:
    print("There is an error in the code")
There is an error in the code

Here vaiable ‘e’ will capture the error.

In [2]:
try:
    a = 1
    b = 0
    a/b
except Exception as e:
    print("There is an error in the code :",e)
There is an error in the code : division by zero

Types of Exception

Python has many built-in exceptions that can be raised at the time of error. Few of them are:

  • SyntaxError: This type of exception is raised when there is an issue with the syntax of the code. For Example, issue with whitespace, type’s, etc.
  • NameError: When we are using some invalid name of variable, functions, etc in code.
  • KeyError: When key is not found in the dictionary.
  • TypeError: When we try to apply some operation on the wrong type of data. Example, adding integer and string.
  • IndexError: When trying to access an invalid index position in list, tuple, etc.

These are the few of many exceptions that can occur.

ZeroDivisionError

In [1]:
a = 1
b = 0
a/b
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-b6249a4a2b4f> in <module>
      1 a = 1
      2 b = 0
----> 3 a/b

ZeroDivisionError: division by zero

TypeError

In [2]:
a = 1
b = 's'
a/b
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-37ff1dc5b147> in <module>
      1 a = 1
      2 b = 's'
----> 3 a/b

TypeError: unsupported operand type(s) for /: 'int' and 'str'

NameError

In [3]:
a = 1
b = 0
a/c
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-86d9473763db> in <module>
      1 a = 1
      2 b = 0
----> 3 a/c

NameError: name 'c' is not defined

Catching Specific Exception

We can have multiple except blocks with each try block. Thanks to these multiple except blocks, we can handle different exceptions differently.

Catching ZeroDivisionError

In [1]:
try:
    a = 1
    b = 0
    a/b
except ZeroDivisionError as e:
    print("There is a division error in the code :",e)
There is a division error in the code : division by zero

Catching NameError

In [2]:
try:
    a = 1
    b = 0
    a/c
except NameError as e:
    print("There is a name error in the code :",e)
There is a name error in the code : name 'c' is not defined

Multiple Except Blocks.
Here TypeError is given the preference because it is not ZeroDivisionError.

In [3]:
try:
    a = 1
    b = 's'
    a/b
except ZeroDivisionError as z:
    print("There is a division error in the code :",z)
except TypeError as t:
    print("There is a type error in the code :",t)
except Exception as e:
    print("There is an exception in the code :",e)
There is a type error in the code : unsupported operand type(s) for /: 'int' and 'str'

On changing the order in which the exceptions are mentioned, output will also change.
Now exception superclass is given the preference.

In [4]:
try:
    a = 1
    b = 'a'
    a/b
except Exception as e:
    print("There is an exception in the code :",e)
except ZeroDivisionError as z:
    print("There is a division error in the code :",z)
except TypeError as t:
    print("There is a type error in the code :",t)
There is an exception in the code : unsupported operand type(s) for /: 'int' and 'str'