Contents

Handling Exceptions in Python

Learn How to Handle Errors and Exceptions in Python Programs

Website Visitors:

Python is a popular programming language that is known for its simplicity and ease of use. However, like any programming language, errors and exceptions can occur while running a Python program. Exception handling is a crucial part of any programming language, and Python is no exception. In this article, we will cover everything you need to know about handling exceptions in Python.

What are Python Exceptions?

In Python, an exception is an event that interrupts the normal flow of a program. When an exception occurs, the interpreter stops executing the program and displays an error message. Some of the most common types of exceptions in Python include NameError, TypeError, and ValueError.

Try-Except Block

To handle exceptions in Python, we use a try-except block. The try block contains the code that might raise an exception, while the except block contains the code to handle the exception.

1
2
3
4
try:
    # code that might raise an exception
except:
    # code to handle the exception

For example, let’s say we want to divide two numbers entered by the user. If the user enters 0 as the second number, a ZeroDivisionError exception will be raised. We can handle this exception using a try-except block as follows:

1
2
3
4
5
6
7
try:
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    result = num1 / num2
    print(result)
except:
    print("Error: Cannot divide by zero.")

Using built-in exceptions

There are some built-in exceptions in python. You can use them if you feel like the error you receive in your try block might be related to them. Checkout the list of all Built-in Exceptions here

1
2
3
4
5
6
7
try:
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))
    result = num1 / num2
    print(result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

Raise Exception

You can also raise exceptions in Python using the raise statement. This can be useful when you want to create custom exceptions for your programs.

1
raise Exception("Custom error message")

Traceback

When an exception occurs in Python, the interpreter displays a traceback, which is a list of function calls that led to the exception. The traceback can help you identify the cause of the exception and fix the error in your program.

except vs except Exception as e

In Python, the except statement is used in a try-except block to catch and handle exceptions that may occur in the try block. There are two main ways to use the except statement: with and without an exception type specified.

When you use except without specifying the exception type, it catches all exceptions that may occur in the try block. This can be useful for catching unexpected errors and preventing your program from crashing. For example:

1
2
3
4
try:
    # some code that might raise an exception
except:
    # handle any exception that occurs

On the other hand, when you use except with an exception type specified, it catches only the specified exception type(s). This allows you to handle different types of exceptions differently. You can also give the exception a name using the as keyword, which allows you to access information about the exception. For example:

1
2
3
4
5
6
try:
    # some code that might raise an exception
except ValueError as e:
    # handle ValueError exception, and access information about it using 'e'
except TypeError as e:
    # handle TypeError exception, and access information about it using 'e'

You can use any alphabet character after as keyword. It doesn’t have to be e character.

So, the main difference between except and except Exception as e is that the latter catches only exceptions of type Exception (and any subclasses of Exception), while the former catches all exceptions that may occur in the try block. Additionally, using as allows you to access information about the exception that was raised, which can be helpful for debugging and error handling.

Let’s start with an example of using except without an exception type specified:

1
2
3
4
try:
    x = 10 / 0
except:
    print("An exception occurred.")

In this code, we attempt to divide the integer 10 by 0, which raises a ZeroDivisionError. Since we haven’t specified an exception type in the except block, it will catch any exception that occurs and print the message “An exception occurred.”

Now let’s look at an example of using except with an exception type specified:

1
2
3
4
try:
    x = "hello" + 10
except TypeError:
    print("A TypeError occurred.")

In this code, we attempt to concatenate the string "hello" with the integer 10, which raises a TypeError. Since we’ve specified the exception type TypeError in the except block, it will catch only TypeError exceptions and print the message “A TypeError occurred.”

Finally, let’s look at an example of using except Exception as e:

1
2
3
4
try:
    x = 10 / 0
except Exception as e:
    print("An exception occurred: ", e)

In this code, we attempt to divide the integer 10 by 0, which raises a ZeroDivisionError. Since we’ve specified Exception as the exception type in the except block, it will catch any exception that occurs and assign it to the variable e. We can then print out the exception message using e. The output of this code would be “An exception occurred: division by zero.”

Another Example:

1
2
3
4
5

try:
    print(10/0)
except ZeroDivisionError:
    print ("ERROR")

Here, output will show as ERROR no matter what kind of error it is. If we use Exception as in the same script,

1
2
3
4
try:
    print(10/0)
except Exception as k:
    print ("ERROR is", k)

Output will be “ERROR is division by zero” because as we have used Exception as in the command, it will pickup the exact exception.

By using as to assign the exception to a variable, we can access information about the exception, such as its message or type. This can be helpful for debugging and error handling.

Using except without an exception type specified catches any exception that may occur in the try block, while using except with an exception type specified catches only the specified exception type(s). Using except Exception as e allows us to access information about the exception that was raised.

Finally block

Finally block always runs whether or not try block or except block raises an error.

1
2
3
4
5
6
try:
    print(10/0)
except ZeroDivisionError:
    print ("ERROR")
finally:
    print("This is end of script")

Suggested Article

If you’d like to continue reading, checkout our other articles on python here or browse all other topics here.

Conclusion

In conclusion, handling exceptions is an essential skill for any Python developer. By using the try-except block, you can catch and handle exceptions in your programs, and by using the raise statement, you can create custom exceptions to make your code more robust. Understanding how to read and interpret the traceback can also help you identify and fix errors in your programs. By following the examples in this article, you can start handling exceptions in your Python programs today.

Your inbox needs more DevOps articles.

Subscribe to get our latest content by email.