Hi everyone, In this tutorial, we’ll be learning about Exception Handling in Python.

1. Exception Handling in Python

In Python, there are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

1.1. Difference between Errors and Exceptions

Errors or mistakes in a program are often referred to as bugs and all the runtime (and syntax) errors that we have encountered are called exceptions. Generally errors are resolved by debugging the code and the exceptions are handled by exception handling. Errors may or may not leads the program to crash whereas in case of exceptions, program execution is terminated at the time of occurence of exception.

1.2. Syntax Errors

Syntax errors cannot be handled and we have to figure out what’s wrong with the code and fix it to move further. For example, missing colon (:).

print("This line prints before error")
for i in range(5)
    print(i)
print("This line prints after error")

Output:

File ".\pyexcept.py", line 2
for i in range(5)
^
SyntaxError: invalid syntax

See how we have missed the colon at the end of the loop in line 2 but line 1 also not gets executed. Once we fix the error, our code will run smoothly.

1.3. Exceptions

The other errors that came under exceptions can be handled using exception handling which terminates the program during execution at the point where the error occurred. For example, NameError, ValueError etc.

print("This line prints before error")
for i in range(5):
    print(a)
print("This line prints after error")

Output:

This line prints before error
Traceback (most recent call last):
File ".\pyexcept.py", line 3, in <module>
print(a)
NameError: name 'a' is not defined

Look at the code above, we have not defined a and tried to print it, NameError occurred at line 3, but see how previous lines got executed successfully.

2. Keywords used to Handle Exceptions in Python

Python language provides us with many keywords which are used in handling exceptions.

  1. try
  2. except
  3. else
  4. finally
  5. raise

2.1 try –

When we are uncertain about the behaviour of a piece of code, we put that code inside a try block to prevent any interruption or termination of the program at runtime. an except block is used which get executed if there is an exception encountered inside the try block.

2.2 except –

Except block is used after the try block to handle the exception occurred in the try block and used to return the appropriate exception without terminating the program. We can use multiple except block for a single try block in our code.

2.2.1  General syntax of try-except clauses

try:
    """ Code here which may cause error 
    """
except (Exception1, Exception2,...):
    """Exception handling code goes here
    """

Let us use the example used in the exception section above and if any NameError occurs, it will handle the exception so that the program does not get terminated. We will use a simple try-except block in this case that we have seen until now.

print("This line prints before error")
for i in range(5):
    try:
        print(a)
    except NameError as ne:
        pass
print("This line prints after error")

Output:

This line prints before error
This line prints after error

So we have successfully handled the exception occurring in the above code. Let’s look at more keywords in Python that are used while handling exceptions.

2.3 else –

The else block executes when there is no exception occurred inside the try block. This block is present after the except blocks. suppose we have created a script that performs division, We know that if we try to divide a number by zero(0), we will get an error. Let’s try to handle that and print the exception in case it occurs else we will print the result of the division.

print("Welcome to OnlinetutorialsPoint")
a=10
for i in range(5):
    try:
        ans = a/i
    except ArithmeticError as ae:
        print("a:",a,", i:",i)
        print("This is an arithmetic error \nMore details\n",ae)
    else:
        print("a:",a,", i:",i)
        print("No exception, Ans is: ",ans)
print("Great Work!!!")

Output:

Welcome to OnlinetutorialsPoint
a: 10 , i: 0
This is an arithmetic error
More details
division by zero
a: 10 , i: 1
No exception, Ans is: 10.0
a: 10 , i: 2
No exception, Ans is: 5.0
a: 10 , i: 3
No exception, Ans is: 3.3333333333333335
a: 10 , i: 4
No exception, Ans is: 2.5
Great Work!!!

2.4 finally –

This is the block that always runs whether there is an exception or not. This block can contain a critical piece of information that is required to run during execution, code to manage memory, etc. Let’s add a finally block in the above code after else block.

print("Welcome to OnlinetutorialsPoint")
a=10
for i in range(3):
    try:
        ans = a/i
    except ArithmeticError as ae:
        print("a:",a,", i:",i)
        print("This is an arithmetic error \nMore details\n",ae)
    else:
        print("a:",a,", i:",i)
        print("No exception, Ans is: ",ans)
    finally:
        print("This if finally block")
print("Great Work!!!")

Output:

Welcome to OnlinetutorialsPoint
a: 10 , i: 0
This is an arithmetic error
More details
division by zero
This if finally block
a: 10 , i: 1
No exception, Ans is: 10.0
This if finally block
a: 10 , i: 2
No exception, Ans is: 5.0
This if finally block
Great Work!!!

From the output above, we see that for every iteration whether we got exception or not finally block always executes.

2.5 raise –

raise is the keyword that is used to forcefully raise an exception at runtime. For example, we are creating software which can not take the integer 2 as a divisor. what we can do some changes in our code manually raise an exception whenever divisor becomes equal to 2.

print("Welcome to OnlinetutorialsPoint")
a=10
for i in range(3):
    try:
        if i==2:
            print("a:",a,", i:",i)
            raise ValueError("Value of divisor cannot be 2 for our System")
        ans = a/i
    except ArithmeticError as ae:
        print("a:",a,", i:",i)
        print("This is arithmetic error \nMore details\n",ae)
    else:
        print("a:",a,", i:",i)
        print("No exception, Ans is: ",ans)
    finally:
        print("This if finally block")
print("Great Work!!!")
Output:
Welcome to OnlinetutorialsPoint
a: 10 , i: 0
This is arithmetic error
More details
division by zero
This if finally block
a: 10 , i: 1
No exception, Ans is: 10.0
This if finally block
a: 10 , i: 2
This if finally block
Traceback (most recent call last):
File ".\pyexcept.py", line 51, in <module>
raise ValueError("Value of divisor cannot be 2 for our System")
ValueError: Value of divisor cannot be 2 for our System

3. User Defined Exceptions

Up until now we have dicussed all about the built-in exceptions that Python provides us. But we can create our own exception class according to our requirement by just creating a class that inherits the pre-defined class Exception. To know more about User defined Exceptions, visit the tutorial here.

So in this tutorial, we see how we can perform exception handling in Python, If you have any doubt, feel free to ask in the comment section.

4. Resources

Happy Learning 🙂

About the Author:

Aspiring Data Scientist who loves Python Programming, Software Development and wants to Solve Real-world Problems.

Leave A Comment