Exception Handling in Python
Exception Handling in Python

Exception Handling in Python

Exception Handling in Python usually makes use of the “try-except” statement. In order to understand this concept, one needs to know the meaning of exceptions and the need for handling them. There are various reasons why we need to handle exceptions. We will discuss them one by one in this article. We will also look at the finally block, custom exceptions and multiple exception clauses.

What are Exceptions in Python?

An exception is an event which sometimes occurs when a python program gets into an error while execution. However, if we handle these exceptions rightly, we can avoid the program from crashing.

What is the need of Exception Handling?

There are many reasons why exception handling is important. Let us look at them one by one.

  1. Avoiding Program Crashing: We may encounter errors in a program during runtime. This makes the program terminate abruptly. But using Exception Handling, we can stop the program from failing and crashing.
  2. Separating Code: To look for a particular block in a program might be tedious. Especially when the program is complex and lengthy. Therefore, instead of looking for error related code, we can put it inside the “except” block. This separates the code needed for error handling and the code having main logic.
  3. Grouping Different Errors: As mentioned above, we put code related to exception handling in “except” block. If we use multiple except blocks, we can separate different kinds of error. This makes the handling of different types of errors easy.

Difference between Exceptions and Syntax Errors in Python

Syntax Error: Syntax error is an error which occurs due to the use of wrong syntax in the code. It directly leads to termination of the program. Here is an example:

Exceptions: Exceptions occur when the code results in an error even when the code is syntactically correct. This does not lead to termination of the program but alters the normal flow. Here is an example:

amount = 100
balance = amount/0
print(balance)

Output:

A number cannot be divided by 0. The error received as a result of this raises an exception.

Try – Except Statement

In order to catch and handle exceptions, we can use Try-Except Statements in Python. The name of this exception is in a pair and its working also follows a pair. The statements that cause an exception are paired and put inside the try clause. While the statements that handle these exceptions are kept inside the except clause.

Syntax:

try:
    # Statements that might cause an exception
except:
    # Statements that will handle these exceptions

Let us look at an example.

arr = [10, 20, 30, 40, 50]
try:
    print("Fourth element is %d" %(a[3]))
    print("Sixth element is %d" %(a[5]))
except:
    print("There is some error")

Output:

Fourth element is 40
There is some error

In this example, we are trying to access an array element whose index is out of bound. The except clause is used to handle this exception. The statements that might result in an error are placed inside the try statement. Any resulting exception is caught by the except statement.

Catching a Specific Exception in Python

For specifying handlers for various exceptions, a try statement can have more than one except clause. In such a case, at most one handler gets executed.

Syntax:

try:
    # statement()
except IndexError:
    # statement()
except ValueError:
    # statement()

Here is a program which handles multiple errors with one except statement.

def myfun(x):
     if x < 10:
          y = x/(x-9)   #this will throw an error for x = 9
     print("y is: ", y)
try:
     myfun(9)
     myfun(12)

except ZeroDivisionError:
    print("ZeroDivisionError encountered but handled")
except NameError:
    print("NameError encountered but handled")

Output:

ZeroDivisionError encountered but handled

In the above program, if the statement myfun(9) is removed, the output will be- NameError encountered but handled.

Suggested Reading: Best Use of Try-Execept in Python

Try with Else Clause in Python

We can also use the else clause on the try-except block. This however, should be placed after all the except clauses. The else block executes if and only if an exception is not raised by the try clause.

Syntax:

try:
    some code....
except:
    some code....
else:
    some code....

Here is an example:

def myfun(x, y):
    try:
        z = ((x+y) / (x-y))
    except ZeroDivisionError:
        print ("x/y gives 0")
    else:
        print(z)

myfun(8, 4)
myfun(4, 4)

Output:

 3
 x/y gives 0

In the above example, we are using the try statement with the else clause. If the exception occurs, the except statement executes. Otherwise, the else statement executes.

Suggested Reading: try-except vs if else in python

Finally Keyword in Python

Like in C, the way do statement always runs once before going in the while loop, statements written inside the finally block always execute after the try and except blocks. Whether the try block terminates normally or due to some exception, the finally block always executes.

Syntax:

try: 
    # Some Code...

except:
    # Some Code...

else:
    # Statements to execute if exception does not occur

finally:
    # Some code which always executes

Let us look at an example:

try:
    x = 47//0
    print(x)

except ZeroDivisionError:
    print("Division with zero is not defined")

finally:
    print("Statements inside finally block always execute")

Output:

Division with zero is not defined
Statements inside finally block always execute

In the above example, the statement inside the try block raises an exception which is handled by the except block. After that, the statement inside the finally block executes.

Raising Exception in Python

To deliberately cause an exception in python, we use raise statement. The sole argument in raise shows the exception that has to be raised. This can be an exception instance or an exception class. It must be noted that an exception class is derived from an exception.

Syntax:

try:
    raise some code...
except:
    some code...
    raise #to reraise

Let us look at an example:

try:
    raise NameError("Avid Python")
except NameError:
    print("Exception occurs")
    raise

The output of this code will simply be “Exception occurs”. But because of the last raise statement, a run time error will also occur. The output looks like this.

Exception occurs
Traceback (most recent call last):
  File "/home/hfkjshs2982952959bfjsiw78gw.py", line 2, in <module>
    raise NameError("Avid Python")
NameError: Avid Python

Conclusion

In this article, we discussed how exceptions are handled in Python. We saw the use of try, catch and finally statements with syntax and example. We also learned the difference between a syntax error and an exception along with the use of raise statement.

To learn more about python programming, you can read this article on list comprehension. You might also like this article on dictionary comprehension in Python.

Leave a Reply