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.
try:
a = 1
b = 0
a/b
except Exception:
print("There is an error in the code")
Here vaiable ‘e’ will capture the error.
try:
a = 1
b = 0
a/b
except Exception as e:
print("There is an error in the code :",e)
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
a = 1
b = 0
a/b
TypeError
a = 1
b = 's'
a/b
NameError
a = 1
b = 0
a/c
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
try:
a = 1
b = 0
a/b
except ZeroDivisionError as e:
print("There is a division error in the code :",e)
Catching NameError
try:
a = 1
b = 0
a/c
except NameError as e:
print("There is a name error in the code :",e)
Multiple Except Blocks.
Here TypeError is given the preference because it is not ZeroDivisionError.
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)
On changing the order in which the exceptions are mentioned, output will also change.
Now exception superclass is given the preference.
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)