Proper Exception Handling in Python Using try, except, and finally Blocks

Posted by Afsal on 22-Dec-2023

Hi Pythonistas!

Exception handling is a crucial aspect of writing robust and reliable Python code. The try, except, and finally blocks provide a structured way to handle errors and ensure that your program gracefully manages exceptional situations. Unlike other languages python has else block in exception handling. Let us dive into the code

try exception block structure

try:
    # Code that may raise an exception
    # ...
except SomeException as e:
    # Code to handle the exception of type SomeException
    # ...
except AnotherException as e:
    # Code to handle a different type of exception
    # ...
else:
    # Code that runs if no exception was raised in the try block
    # ...
finally:
    # Code that always runs, whether an exception was raised or not
    # This block is optional
    # …

The try Block

The try block encloses the code that may raise an exception. It's the segment of your code where potential errors are anticipated.

The except Block

The except block is used to handle specific exceptions. You can have multiple except blocks to address different types of exceptions. The as keyword is optional but allows you to capture the exception instance for further examination or logging.

The else Block

The else block contains code that runs if no exception was raised in the try block. It is optional but can be useful for separating the normal code flow from the exception-handling logic.

The finally Block

The finally block contains code that always runs, whether an exception was raised or not. This block is optional but is commonly used for cleanup tasks, such as closing files or network connections.

Code

def divide():
    try:
        x = int(input("Enter a number: "))
        result = 10 / x
    except ValueError:
        print("Invalid input. Please enter a valid number.")
    except ZeroDivisionError:
        print("Cannot divide by zero.")
    else:
        print("Result:", result)
    finally:
        print("This will always execute.")

Output

>>> divide()
Enter a number: 10
Result: 1.0
This will always execute.
>>> divide()
Enter a number: add
Invalid input. Please enter a valid number.
This will always execute.
>>> divide()
Enter a number: 0
Cannot divide by zero.
This will always execute.
>>>

In the first case entered value is 10 so there is no exception hence else block is executed and finally block executed

In the second case entered value is ‘add’ which is not valid number hence ValueError exception block get executed and finally block executed

In the third case entered value is 0 so the ZeroDivisionError exception block executed then finally get executed

Note: Do Not use wildcard exceptions in code. We have a post regarding that please click here to read.

I hope you have learned something from this post. Please share your valuable suggestion with afsal@parseltongue.co.in