Exception Handling in Python

Python : Exception Handling

Exception handling is an important part of writing robust and reliable code in Python.

What is Exception in Python?

Exceptions are runtime errors that occur when your code encounters an unexpected situation.

Take an example, trying to divide a number by zero will raise a ZeroDivisionError. In Python, we can use try-except blocks to handle exceptions.

Syntax of a try-except block:

try:
    # code that may raise an exception
except ExceptionType:
    # code to handle the exception

The try block contains the code that may raise an exception, and the except block contains the code to handle the exception. The ExceptionType is the type of exception that the except block will handle. You can specify multiple except blocks to handle different types of exceptions.

Handling Exceptions in Python:

There are several ways to handle exceptions in Python:

  1. Using try-except blocks:

    We can use try-except blocks to handle exceptions in our code. This is the most common way to handle exceptions in Python.

  2. Using finally block:

    We can use the finally block to execute code that should be run regardless of whether an exception occurred or not.

  3. Raising exceptions:

    We can raise exceptions ourselves using the raise keyword. This is useful when we want to indicate that an error occurred in our code.

  4. Using the assert statement:

    The assert statement is used to check if a condition is true, and if it is not true, it raises an AssertionError.

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print("Error: division by zero")
    else:
        print("Result is", result)
    finally:
        print("Execution complete")

In the above example, we have defined a function called divide that takes two arguments x and y. We use a try-except block to handle the ZeroDivisionError that can occur when y is zero. If no exception occurs, we print the result, and if an exception occurs, we print an error message. The finally block is used to execute code that should be run regardless of whether an exception occurred or not.

Previous Article