Home
About Us Privacy Policy
 

EXCEPTION HANDLING IN PYTHON

ADVERTISEMENT

Advanced Exceptions



What are Exceptions in Python, and why are they required?

In Python, program execution errors are called Exception(s). If the Exceptions are not explicitly handled, they will halt program execution.

Python provides four keywords to manage Exceptions:

  • try
  • catch
  • finally
  • raise

The finally clause is optional and can be omitted.


Syntax

try:
        statement 1
        statement 2
        statement 3
        ...
        ...
        statement N
except <ExceptionName> as <identifier>:
        statement 1
        statement 1
        ...
        statement N
finally:
        statement 1
        statement 2
        statement ...
        statement N

The <ExceptionName> is optional and can be omitted.
The as <identifier> clause is optional and can be omitted.


Now let's discuss the different components of Python's exception handling mechanism.

try

This block will contain the code that has the possibility of generating an exception.

except

This block will handle the appropriate Exception. It can include the exception name to address the respective Exception differently.

For example, if the code in the try block can generate ZeroDivisionError and can also cause IndexError. The appropriate exception block will catch it. Below is an example.

try:
    n = int(input("Enter a number:\n"))
    m = int(input("Enter another number:\n"))
    my_list = [1, 2, 3, 4]
    r = n // m
    print(my_list[r])
except ZeroDivisionError:
    print("Cannot Divide By 0")
except IndexError as e:
    print(
        "Index is greater than", 
        len(my_list), 
        "The following message was generated: ", 
        e
    )

Enter a number:
8
Enter another number:
4
3


finally

This block gets executed irrespective of whether the Exception was generated or not. It is optional. The finally block can be handy for closing resources such as File Handles or Network Connections.


raise

The raise statement generates an exception. Below is the syntax:

try:
    m = int(input("Enter a number:\n"))
    if m != 8:
        raise Exception("This is not the required number. ")
    print("The number is 8")
except Exception as e:
    print(e)
finally:
    print("Bye")

Enter a number:
34
This is not the required number.
Bye


ADVERTISEMENT

Managing multiple Exceptions

Python allows for managing multiple exceptions. It is advantageous as a program can generate different exceptions and thus should be handled differently. For example, ZeroDivisionError should be handled differently than IndexError.

Example:

try:
    n = int(input("Enter a number:\n"))
    m = int(input("Enter another number:\n"))
    print(f"n/m is {n/m}")
    print(f"n*m is {n*m}")
except ZeroDivisionError:
    print("Cannot Divide By 0")
except IndexError as e:
    print(
         "Index is greater than", 
         len(my_list), 
         "The following message was generated: ", 
         e
    )

Enter a number:
5
Enter another number:
4
n/m is 1.25
n*m is 20


ADVERTISEMENT

What advantage does Exception Handling provide?

During the development of large programs, there are numerous instances where a bug might seep through and cause incorrect processing leading to malfunctioning software for the end-user, leading to loss of opportunity, reputation, finance, etc.

One of the notable examples is the Y2K problem. You can read more about that here.

Exception handling solves such instances by catching such errors as they occur and halt any further execution unless explicitly handled.


Built-In Exceptions

Python provides several in-built exceptions. The most common are:

  1. IndexError
  2. ZeroDivisionError
  3. IndentationError
  4. NameError

You can go through the entire list of exceptions in Python here.


Raising Custom Exceptions and Sending Custom Messages

Although there are several in-built Exceptions in Python, they might not be suitable for every scenario. To handle such instances, Python provides the ability to raise custom Exceptions with messages. Although we can implement our custom Exception, I won't describe the process here because it requires knowledge of Classes, an uncovered topic. However, if you are curious, you can refer to this article.

To send a Custom message in an Exception, Python provides the raise keyword.

Here is an example.

is_magic_number_not_found = True
while is_magic_number_not_found:
    try:
        m = int(input("Guess the magic number: \n"))
        if m != 1000:
            raise Exception("This is not the required number. ")
        print("Voila! You found the magic number. It's 1000. ")

        # Switch the status to False to
        # stop the loop execution
        is_magic_number_not_found = False
    except Exception as e:
        print(e)
    finally:
        print("Bye")

Guess the magic number:
6
This is not the required number.
Bye
Guess the magic number:
4
This is not the required number.
Bye
Guess the magic number:
100
This is not the required number.
Bye
Guess the magic number:
1000
Voila! You found the magic number. It's 1000.
Bye


ADVERTISEMENT

Conclusion

In this chapter, we learned about Exceptions in Python and their importance and usage. We also learned the syntax of managing exceptions, explained Exception's different components, handled raised Exceptions, managed multiple Exceptions.

We also learned several advantages of using Exceptions to handle unpredictable error conditions, explained few in-built exceptions, and raised Exceptions with business-related(custom) messages for conciseness.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.