DEV Community

Cover image for Python Exception Handling: How to Use try-except to Catch Errors
Javier Madriz
Javier Madriz

Posted on

Python Exception Handling: How to Use try-except to Catch Errors

What's an exception?

An exception is an unexpected event or error that disrupts the normal flow of a program's execution.

What is Exception Handling?

Python comes with a built-in syntax called try...except that allows you to handle errors and prevent them from interrupting the execution of your program.

This means that if your program consists of multiple blocks, catching an error enables the rest of the blocks to execute even if there was an error in a specific block. This prevents the entire program from being interrupted completely.

Python has many built-in exceptions, such as IndexError, NameError, TypeError, ValueError, ZeroDivisionError, KeyError, and many more.

There are different ways to catch exceptions, ranging from basic to more advanced techniques. Let's explore them

division = None
try:
    division = 10 / 0
except:
    print('An error of division by zero was detected')

Enter fullscreen mode Exit fullscreen mode

This code block demonstrates exception handling in Python, allowing the printing of a custom message when an exception occurs. However, there are better practices for exception handling, such as identifying and handling specific exceptions. This provides more precise control over how errors are managed in the program and contributes to its stability.

let's see another way:


division = None
try:
    division = 10 / 0
except Exeption as error:
    print(f'An error occurred: {error}')
Enter fullscreen mode Exit fullscreen mode

This code block uses except Exception, which is more general and will catch any exception that is a subclass of Exception. In Python, all exceptions are subclasses of Exception, so this block will capture virtually any type of exception and display the default message associated with each exception, as defined in Python.

However, it is essential to mention that, in general, it is good practice to be specific in exception handling and only catch those types of exceptions that you expect and know how to handle. This way, you can avoid catching unexpected exceptions and handle errors more precisely.

let's see the best way:

division = None
try:
    division = 10 / 0
except ZeroDivisionError as error:
    print(f'An error occurred: {error}')
Enter fullscreen mode Exit fullscreen mode

In this code block, we are exploring a more specific and precise way of handling exceptions. By using except ZeroDivisionError, we are capturing only the specific exception type ZeroDivisionError. This means that only this type of exception will be caught.

It is important to note that ZeroDivisionError is a subclass of Exception, which means that any exception of type ZeroDivisionError is also an exception of type Exception. When using except Exception, you capture both ZeroDivisionError exceptions and any other exceptions that may occur, including ValueError, TypeError, and so on.

By using except ZeroDivisionError, we ensure that only division by zero errors will trigger this specific exception handling, while other exceptions can be handled separately if needed.

How about creating a complete script, defining a function with exception handling, and then observing the output in the console?

def sum_list(num_list):
    result = 0
    try:
        result = sum(num_list)
    except TypeError as e:
        print(f'An error occurred: {e}')

    return result


if __name__ == '__main__':
    results = sum_list([1,2,3,4,5,6,7,8,'j'])
    print(results)
Enter fullscreen mode Exit fullscreen mode

Explanation:

Our function sum_list takes a list of numbers and attempts to sum them. This action is wrapped within a try-except block using the TypeError subclass, ensuring that all elements in the list are numbers; otherwise, an exception will be caught.

In this script, we call the sum_list function with a list [1, 2, 3, 4, 5, 6, 7, 8, 'j'], which contains a string ('j') along with numeric elements. When the sum function is applied to this mixed list, it raises a TypeError, as it cannot perform a numeric sum with a non-numeric element.

The except block captures this TypeError, and the error message is printed to the console. As a result, the script does not terminate abruptly due to the exception.

Output: Handling a TypeError Exception in Python
Image description

Conclution

In conclusion, exception handling in Python is crucial for managing errors and ensuring a more stable program execution. Using try-except blocks allows capturing and dealing with specific exceptions, providing informative error messages for debugging and enhancing user experience. Proper exception handling makes our programs more reliable and resilient to unexpected situations

Top comments (0)