≡ Menu

5 Python Examples to Handle Exceptions using try, except and finally

[Python Exception Handling]Exceptions in python are error thrown by syntactically correct statements.

They terminate the execution of the script. Some example of exceptions are NameError, TypeError, AssertionError, ConnectionAbortedError, etc.

These abortions can be handled to prevent the script from terminating unpredictable. Description of all python exceptions can be found here.

This tutorial covers the following examples:

  1. Python try-except Block
  2. Multiple Exception Handling in Python
  3. Python finally Block – When Exception Occurs
  4. Python finally Block – When No Exception
  5. Python Nested try-except Block

Have a look at the following code:

t
a = 12
s = "hello"
print(a+s)

Output:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Here the print function syntax is correct, yet addition of an integer and a string is incorrect. Hence TypeError is raised by python interpreter.

1. Python try-except Block

The keywords involved in handling of exceptions are try, except and finally.

Try block must be followed by an except block. Addition of finally block is optional.

The statements in the try block are executed line by line. If execution of any statement throws an exception. The remaining statements in this block are skipped and execution of except block starts.

Example:

a = 12
s = "hello"
try:
    print("inside try")
    print(a + s) # will raise TypeError
    print("Printed using original data types")
except TypeError: # will handle only TypeError
    print("inside except")
    print(str(a) + s)
    print("Printed using type-casted data types")

Output:

inside try
inside except
12hello
Printed using type-casted data types

Here TypeError was raised in the execution of line 2 inside try block. Hence execution of remaining statements was skipped and except block execution started. Note that the exceptions to be handled are mentioned along side the except keyword.

If you are new to python, this might help you get a jumpstart: 5 Examples to Jumpstart Object Oriented Programming in Python

2. Multiple Exception Handling in Python

Multiple exceptions can be handled using a single try-except block. This is done by mentioning the exception names, comma-separated inside parentheses, just after except keyword.

try:
    if (3 + 4 - 5) > 0:
        a = 3
        a.append("hello")  # throws AttributeError
    else:
        print("hello" + 4)  # throws TypeError
except (AttributeError, TypeError) as e:
    print("Error occurred:", e)

Output:

Error occurred: 'int' object has no attribute 'append'

For more details python if-else, refer to this: 9 Python if, if else, if elif Command Examples

3. Python finally Block – When Exception Occurs

finally is the block that resides after except block. This block of statements is executed no matter whether an exception was encountered or not.

Adding finally block to the previous example:

try:
    if (3 + 4 - 5) > 0:
        a = 3
        a.append("hello")  # throws Attribute Error
    else:
        print("hello" + 4)  # throws TypeError
except (AttributeError, TypeError) as e:
    print("Error occurred:", e)
finally:
    print("try except block successfully executed")

Output:

Error occurred: 'int' object has no attribute 'append'
try except block successfully executed

Here the statements in try raised an exception, except block was executed and then the finally block.

4. Python finally Block – When No Exception

Having a look at another example:

try:
    if (3 + 4 - 5) < 0:
        a = 3
        print(a + 5)  # simple addition
    else:
        print("hello" + "4")  # string concatenation
except (AttributeError, TypeError) as e:
    print("Error occurred:", e)
finally:
    print("try except block successfully executed")

Output:

8
try except block successfully executed

Here we see that finally block was executed even if the except block was never executed.

If statements inside except and finally block raises exception, the remaining script execution will terminate.

5. Python Nested try-except Block

A try-except block can be surrounded by another try-except block.

import json
import sys

try:
    with open("hello.json") as fp:
        try:
            json_dict = json.load(fp)
        except json.JSONDecodeError:
            print("Json file does not exist")
    print(json_dict)
except:
    print("error occurred while parsing json:", sys.exc_info()[1])

Output: if hello.json exists

{'name': 'Aanisha', 'surname': ‘Mishra'}

Output: if hello.json does not exist

error occurred while parsing json: [Errno 2] No such file or directory: 'hello.json'

Output: if hello.json is not a valid json file

Json file does not exist
error occurred while parsing json: name 'json_dict' is not defined

This form of solution can handle exception raised inside except or finally block as well.

For additional reading, more detailed handling strategies can be found here.

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 0 comments… add one }

Leave a Comment