Exception Handling in Python

FREE Online Courses: Click, Learn, Succeed, Start Now!

We all would have come across some exceptions while coding. Did you ever wonder how many types of exceptions exist and how to deal with these exceptions?

We will be discussing the exceptions in Python and also see different ways to handle these. Let us start with the introduction part. Also, in the end, we will learn briefly about assertion.

What are Python Exceptions?

Exceptions are the unusual event that occurs during the execution of the program that interrupts the normal flow of the program. Generally, exceptions occur when the code written encounters a situation it cannot cope with.

Whenever an exception is raised, the program stops the execution, and thus the further code is not executed. Therefore, an exception is a python object that represents a run-time error. An exception is a Python object that represents an error.

As said before, the code after the line where the exception occurs will not be executed. Don’t worry. We have a solution for this. Python provides a way to handle the exception so that the code gets executed without any interruption. Before learning these ways, let us see different exceptions we have come across or we might in future.

Sr.No. Exception  Description
1 Exception It is the base class for all the exceptions
2 StopIteration It occurs when the next() method of an iterator does not point to any object.
3 SystemExit This occurs by the sys.exit() function.
4 StandardError This is the base class for all built-in exceptions, except StopIteration and SystemExit.
5 ArithmeticError It is the base class for all errors related to the numeric calculation.
6 OverflowError It occurs when a calculation exceeds maximum limit for a numeric type.
7 FloatingPointError This gets raised when a floating point calculation fails.
8 ZeroDivisionError It gets raised when we try to divide or find modulus by zero. It takes place for all numeric types.
9 AssertionError It gets raised when the Assert statement fails.
10 AttributeError This gets raised when attribute reference or assignment fails.
11 EOFError It gets raised when there is no input from either the raw_input() or input() function and the end of file is reached.
12 ImportError It gets raised when an import statement fails.
13 KeyboardInterrupt This gets raised when the user interrupts the program execution, usually by pressing Ctrl+c
14 LookupError It is the base class for all lookup errors.
15 IndexError It gets raised when an index is not in the range of the length of a sequence.
16 KeyError This gets raised when the specified key is not found in the dictionary.
17 NameError It gets raised when an identifier is not found in the local or global namespace.
18 UnboundLocalError It gets raised when we try to access a local variable in a function or method but no value has been assigned to it.
19 EnvironmentError This is the base class for all exceptions that occur outside the Python environment.
20 IOError It gets raised when an input/ output operation fails. For example, when the open() function tries to open a file that does not exist.
21 OSError It is related to operating system-related errors.
22 SyntaxError This gets raised when there is an error in Python syntax.
23 IndentationError It gets raised when indentation rules are not followed.
24 SystemError It gets raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exist.
25 SystemExit This gets raised when the Python interpreter quits by using the sys.exit() function. And if this is not handled in the code, it causes the interpreter to exit.
26 TypeError It gets raised when an operation or function is done on the operands of that datatype on which the operation/function cannot be applied.
27 ValueError It gets raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified.
28 RuntimeError This gets raised when a generated error does not fall into any category.
29 NotImplementedError It gets raised when an abstract method that needs to be implemented in an inherited class is not actually implemented.

When the exceptions are not handled?

If we do not include any code to handle the possible exception, then the program execution will get interrupted. Let us see a common example, where we try to print the value of the variable that is not present.

Example of exception:

num=10
print("The number is:",Num)

Output:

NameError Traceback (most recent call last)
<ipython-input-1-5456d22a2ecc> in <module>
1 num=10
—-> 2 print(“The number is:”,Num)
NameError: name ‘Num’ is not defined

Here, the identifier ‘num’ is written wrongly as ‘Num’ in the print statement. We know that Python is case-sensitive. So, we get an error.

Try and Except in Python

Try and Except statements have been used to handle the exceptions in Python. The try block has the code to be executed and if any exception occurs then the action to perform is written inside the catch block. The syntax is:

try:
    Statements to be executed
except:
    Statements get executed if an exception occurs

Let us see an example.
Example of Python try and except statement:

num=10

try:
    print("The number is:",Num)
except:
    print("An exception occurred")

Output:

An exception occurred

Because the Num variable does not exist, the except statement catches the exception and the code under it gets executed.

Execution Flow on using try/except block

Now, let us see what happens to the code written after this statement.

Example of try and except statement:

num=10

try:
    print("The number is:",Num)
except:
    print("An exception occurred")
    
print("This is a statement present outside the try/except statement ")

Output:

An exception occurred
This is a statement present outside the try/except statement

We can see that the execution does not stop abruptly, but it continues even when an exception occurs due to the presence of the try/except statement. But we cannot put statement(s) between try and except blocks, we get an error.

Example of try and except statement:

num=10

try:
    print("The number is:",Num)
print("This is a statement present outside the try/except statement ")
except:
    print("An exception occured")

Output:

File “<ipython-input-10-b5339652b683>”, line 5
print(“This is a statement present outside the try/except statement “)
^
SyntaxError: invalid syntax

Python Printing Exception Details

We can also print the exception details. This can be done by using an exception variable.

Example of try and except statement with exception variable:

num=10

try:
    print("The number is:",Num)
except Exception as e:
    print("The exception is:",e)

Output:

The exception is: name ‘Num’ is not defined

Catching Multiple Exceptions in Python

In the above examples, we could catch exceptions. In addition, Python also facilitates us to check for particular exception(s). Let us discuss them in this section.

Catching Specific Exceptions

We can have multiple except statements, each dealing with a specific exception of our interest. The syntax for this is:

try:
    Statements to be executed
    ......................
except ExceptionI:
   If ExceptionI occurs, this block gets executed.
except Exception2:
   If Exception2 occurs, this block gets executed.
                                     :
                                     :
                                     :

Let us see an example.

Example of try and except statement with specific exceptions:

num=10

try:
    div=num/0
except ZeroDivisionError:
    print("Zero cannot be in the denominator")
except SyntaxError:
    print("There is some error in the syntax")

Output:

Zero cannot be in the denominator

If we would have done some syntax mistake, then the second except block would have got executed.

Multiple Exception in One Except Block

We can also have multiple exceptions handled under a single except block and the syntax for this is:

try:
   Statements to be executed
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there are any of the specified exceptions, then this block gets executed.
                                     :
                                     :
                                     :

Example of try and except statement with multiple exceptions in one block:

num=10

try:
    div=num/0
except (ZeroDivisionError,TypeError):
    print("Invalid operands for division")

Output:

Invalid operands for division

Generic Except Block in Python

In addition to catching a specific exception, we can also add an except block to execute if any other errors occur. The syntax for this is:

Example of try and except statement with specific exceptions and a genetic except block:

num=10

try:
    div=Num/0
except (ZeroDivisionError,TypeError):
    print("Invalid operands for division")
except:
    print("Any other exception occurred")

Output:

Any other exception occurred

Python Try with else clause

We can also have else block along with the try/except blocks. The code in the else block executes only if the code in the try block does not result in an exception.

Example of try with else clause:

num=10

try:
    div=num/2
except:
    print("An exception occurred")
else:
    print("The value is",div)

Output:

The value is 5.0

Finally Keyword in python

Finally is another addition to the try/except blocks. The statements in this block execute independently of the execution of the code in the try block. The syntax for this is:

try:
    Statements to be executed
   ......................

except:
    # optional block
    Statements get executed if an exception occurs

else:
    Statements get executed if no exception

finally:
    Statements get executed always

Example of try with finally keyword:

num=10

try:
    div=num/0
except:
    print("An exception occurred")
finally:
    print("This is finally block")

Output:

An exception occurred
This is finally block

Raise Exception in Python

We can also raise a specific exception by using the raise keyword. Let us see what happens when we do that with some examples.

Example of raising an exception:

raise NameError

Output:

NameError Traceback (most recent call last)
<ipython-input-8-42b67b2fc75d> in <module>
—-> 1 raise NameError
NameError:

Example of raising an exception:

num=-3
if(num<0):
    raise TypeError

Output:

TypeError Traceback (most recent call last)
<ipython-input-9-63f45332ff27> in <module>
1 num=-3
2 if(num<0):
—-> 3 raise TypeError
TypeError:

Similarly, we have different options that Python provides while raising these exceptions. Let us see them.

Raising a generic exception

We can raise a generic exception by just using the raise keyword.

Example of raising a generic exception:

raise

Output:

RuntimeError Traceback (most recent call last)
<ipython-input-12-9c9a2cba73bf> in <module>
—-> 1 raise
RuntimeError: No active exception to reraise

When we use with the try/except block, we get the exception occurred.

Example of raising a generic exception:

num=-3
try:
    num/0
except:
    raise

Output:

ZeroDivisionError Traceback (most recent call last)
<ipython-input-11-8b1d643bbd20> in <module>
1 num=-3
2 try:
—-> 3 num/0
4 except:
5 raiseZeroDivisionError: division by zero

Raising with an argument

We can also give an argument to the exception raised using the raise keyword.
Example of raising an exception with an argument:

raise NameError("The variable does not exist ")

Output:

NameError Traceback (most recent call last)
<ipython-input-13-52da815ba28f> in <module>
—-> 1 raise NameError(“The variable does not exist “)
NameError: The variable does not exist

Example of raising an exception with an argument:

num=-3
try:
    if(num<0):
        raise TypeError("Invalid number")
except Exception as e:
    print(e)

Output:

Invalid number

Assertions in Python

An assertion is a sanity check that can be turned on or off when you are done with your testing of the program. It takes an expression, tests it, and if the result comes up false, it raises an exception. We can use the assert statement, the keyword introduced in Python version 1.5. The syntax is:

assert Expression[, Arguments]

Example of assertion:

assert True

Example of assertion:

n=-5
assert n>0

Output:

AssertionError Traceback (most recent call last)
<ipython-input-23-1df8cef3b196> in <module>
1 n=-5
—-> 2 assert n>0
AssertionError:

We can also use it with the try/except block.

Example of assertion in try/except block:

try:
    n=0
    print(n)
    assert n==0
    assert n>0
    
except:
    print("An assert failed.")
    raise
finally:
    print("final")
print("End")

Output:

0
An assert failed.
final—————————————————————————
AssertionError Traceback (most recent call last)
<ipython-input-24-dded468e035d> in <module>
3 print(n)
4 assert n==0
—-> 5 assert n>0
6
7 except:
AssertionError:

Since the ‘n’ value is not greater than 0, we get an AssertionError and hence the except block gets executed.

User-Defined Exceptions in Python

We can also define our own exceptions in Python. We can do this by creating a class and when we want to raise that exception we can call that class.

Example of Python user defined exceptions:

class MyException(Exception):
    print('My exception occurred')

raise MyException

Output:

My exception occurred

—————————————————————————
MyException Traceback (most recent call last)
<ipython-input-25-c6303782feb3> in <module>
2 print(‘My exception occured’)
3
—-> 4 raise MyException

MyException:

Interview Questions on Exception Handling in Python

Q1. Write a try/except statement that gives detail of that exception when we try to convert an integer into a list.
Ans. Below is the example:

try:
    seq=list(1)
except Exception as e:
    print("The exception is:",e)

Output:

The exception is: ‘int’ object is not iterable

Q2. Write a try/except statement to deal with multiple exceptions when we try to add two values.
Ans. Below is the example:

try:
    res=1+'5'
except (ZeroDivisionError,TypeError):
    print("Invalid operands")

Output:

Invalid operands

Q3. Write a try/except statement with else statement to return the value of a list if the index lies in the correct range.
Ans. Below is the example:

list1=[1,2,3,4,5]

try:
    val=list1[4]
except:
    print("An exception occurred")
else:
    print("The value is",val)

Output:

The value is 5

Q4. Write a program to raise an error when the user enters empty input.
Ans. Below is the example:

try:
    ip=input("Enter input: ")
    if(ip==''):
        raise TypeError('Enter proper Input')
        
except Exception as exp:
    print(exp)

Output:

Enter input:
Enter proper Input

Q5. Write a program that consists of a user defined exception that occurs when the length of the string is more than 10.
Ans. Below is the example:

class LengthExceeded(Exception):
    print('Length of the string is more than the max allowed length')

string='abcderfhjakljakasfh'

try:
    if(len(string)>10):
        raise LengthExceeded
        
except Exception as exp:
    print(exp)

Output:

Length of the string is more than the max allowed length

Quiz on Exception handling in Python

Conclusion

This is the end of the article on Python Exception Handling. We have seen different exceptions and have seen different methods to handle these. We also learned about assertions and user-defined exceptions.

Happy learning!

Did you like this article? If Yes, please give PythonGeeks 5 Stars on Google | Facebook


1 Response

  1. Rahul says:

    nice tutorial

Leave a Reply

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