Monday, February 3, 2020

Python Exception Handling - try,except,finally

In this article we’ll see how to handle exceptions in Python using try, except and finally statements.

Python exception handling

To handle exception in Python you can use the following procedure-

  1. Use try block to enclose code that might throw an exception.
  2. Use except block to handle the raised exceptions.
  3. Use finally clause to perform clean up like closing the opened file.

General form of exception handling in Python using try, except finally is as follows.

try: 
 try suite
               
except Exception1:
 handler suite
except Exception2:
 handler suite
else:
 else suite
finally: 
 finally suite

Some important points to note here are-

  1. If no exception is raised then the statements in the else block are executed.
  2. Else and finally blocks are not mandatory.
  3. You can have multiple except blocks to handle multiple exceptions.
  4. try block must be followed either by except or finally.
  5. If finally block is there it is always executed whether an exception is raised or not.

Using try, except for exception handling

Let’s try to understand how exception handling in Python using try and except helps in writing robust code. Here is an example where a list is passed to a function and every element in the list is used to divide a number. Just notice what happens if one of the number in the list is zero.

def divide_num(num_list):
  for num in num_list:
    print(10/num)

num_list = [5, 6, 0, 7]
divide_num(num_list)

Output

2.0
1.6666666666666667
Traceback (most recent call last):

  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 6, in <module>
    divide_num(num_list)
  File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 3, in divide_num
    print(10/num)
ZeroDivisionError: division by zero

As you can see dividing by zero raises ZeroDivisionError, since code doesn’t provide any exception handling code of its own so default exception handling is used. Default behavior for handling such exceptions in Python is for the interpreter to print the full stack traceback, that includes the exception type (at least in case of built-in exception) and error message, and then terminate the program.

As you can see program is terminated and only the exception message is displayed by the default exception handling which is not that user friendly.

Python exception handling with try, except

Now let’s write that same code by providing exception handling with in the code using try and except.

def divide_num(num_list):
  for num in num_list:
    try:
      print(10/num)
    except ZeroDivisionError as error:
      print(error)
      print('Zero is not a valid argument here')
    else:
      print('in else block')

num_list = [5, 6, 0, 7]
divide_num(num_list)

Output

2.0
in else block
1.6666666666666667
in else block
division by zero
Zero is not a valid argument here
1.4285714285714286
in else block

As you can see now the code that may throw an exception is enclosed with in a try block. When the exception is raised in the try block exception handler looks for the except block that can handle the exception of that type. In the code ZeroDivisionError is raised and there is an except block that handles ZeroDivisionError so that except block handles the raised exception. Program is not terminated now when the exception is raised because of the exception handling in the code.

except block in Python

There are various ways to write except block while writing exception handling code in Python.

  1. You can catch the exception as an object that gives description about the raised exception.
     except ZeroDivisionError as error:
     
  2. You can write except block with the exception class name only.
     except Exception_Class_Name:
     
  3. You can handle multiple exceptions by using multiple except blocks or you can use a single except block and write multiple exceptions as a tuple.

    For example multiple except blocks-

    except ZeroDivisionError as error:
      print(error)
      print('Zero is not a valid argument here')
    except TypeError:
      print('Argument is not of valid type') 
      

    Single except block with multiple exceptions

      except (ZeroDivisionError, TypeError):
      
  4. You can write except with out specifying exception class. That way except block catches any type of exception. Though that is not considered good practice as it is too broad exception clause and you won’t be able to determine specifically which exception has been raised.
      except:
        print('An exception has occurred')
      

Multiple except block Python example

def divide_num(num_list):
  for num in num_list:
    try:
      print(10/num)
    except ZeroDivisionError as error:
      print(error)
      print('Zero is not a valid argument here')
    except TypeError as error:
      print(error)
      print('Argument is not of valid type-', num)

num_list = [5, 6, 'a', 7]
divide_num(num_list)

Output

2.0
1.6666666666666667
unsupported operand type(s) for /: 'int' and 'str'
Argument is not of valid type- a
1.4285714285714286

finally in Python exception handling

If finally is present, it specifies a ‘cleanup’ handler. The finally clause is always executed whether an exception is raised in the try block or not. That ensures that all the resources are properly cleaned up.

def divide_num(num):
  try:
    f = open("testfile", "a")
    r = 10/num
    f.write("Result 10/%d is %d" %(num,r))
  except ZeroDivisionError as error:
    print(error)
    print('Zero is not a valid argument here')
  except FileNotFoundError as error:
    print(error)
    print('Passed file does not exist')

  finally:
    print('closing file')
    f.close()

divide_num(0)

Output

division by zero
Zero is not a valid argument here
closing file

If function is called with a valid argument and no exception is raised even then finally block is executed. For example calling function as given here.

divide_num(2)

Output

closing file

If there is a return, break or continue statement in try block even then finally clause is executed.

def divide_num():
  try:
    return 'try'
  finally:
    print('In finally clause')

a = divide_num()
print(a)

Output

In finally clause
try

If there is a return statement in finally too then that becomes the last return statement to be executed. Since the return value of a function is determined by the last return statement executed so value returned by finally clause is the value returned by the function.

def divide_num():
  try:
    return 'try'
  finally:
    print('In finally clause')
    return 'finally'

a = divide_num()
print(a)

Output

In finally clause
finally

That's all for this topic Python Exception Handling - try,except,finally. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. raise Statement in Python Exception Handling
  2. Passing Object of The Class as Parameter in Python
  3. Encapsulation in Python
  4. Abstract Class in Python
  5. Strings in Python With Method Examples

You may also like-

  1. Magic Methods in Python With Examples
  2. Check if String Present in Another String in Python
  3. Keyword Arguments in Python
  4. Python Program to Display Fibonacci Series
  5. Java Collections Interview Questions And Answers
  6. this Keyword in Java With Examples
  7. What is Hadoop Distributed File System (HDFS)
  8. Spring Object XML Mapping (OXM) JAXB Example