Try / Except Block in Python

A try/except block in Python is a fundamental construct used to handle exceptions, which are unexpected events that can occur during the execution of a program. This construct allows developers to manage errors gracefully and maintain the flow of the program without abrupt terminations.

Structure of a Try/Except Block

The basic structure of a try/except block is as follows:

try:
    # code that might raise an exception
except Exception as e:
    # code that executes if an exception occurs
else:
    # code that executes if no exception occurs (optional)
finally:
    # code that executes whether an exception occurs or not (optional)
  • try block: Contains the code that might raise an exception.
  • except block: Handles the exception if it occurs. The exception is intercepted and can be assigned to a variable (commonly e).
  • else block: Executes if no exception occurs (optional).
  • finally block: Executes regardless of whether an exception occurred or not (optional).

Example of Handling Exceptions

Consider the following example, which demonstrates handling exceptions in a program that performs division:

def func_a():
    dividend = float(input("Enter a dividend value: "))
    divisor = float(input("Enter a divisor value: "))
    result = func_b(dividend, divisor)
    print(f"dividing {dividend} by {divisor} = {result}")
 
def func_b(dividend: float, divisor: float) -> float:
    return func_c(dividend, divisor)
 
def func_c(dividend: float, divisor: float) -> float:
    return dividend / divisor
 
successful = False
while not successful:
    try:
        func_a()
    except ZeroDivisionError as e:
        print(f"The divisor can't be a zero value, error:", e)
    except ValueError as e:
        print(
            f"The dividend and divisor must be a string that represents a number, error:",
            e,
        )
    else:
        successful = True
    finally:
        if successful:
            print("Thanks for running the program")
        else:
            print("Try entering a dividend and divisor again")

In this example, the program prompts the user for a dividend and a divisor, then attempts to divide them. If a ZeroDivisionError or ValueError occurs, the program informs the user and prompts for input again. The finally block ensures a message is printed regardless of the outcome.

Handling Exceptions

Making Reasonable Choices

When an exception occurs, the handler can make reasonable choices within the context of the function. For instance, it might retry the operation or correct the state of data to continue execution without raising an exception.

Allowing Exceptions to Flow Upward

If the code where the exception occurs cannot handle it meaningfully, it is often better to let the exception flow upward through the call stack. This allows higher-level contexts to make decisions about handling the exception, such as retrying operations or informing the user.

Informing Users

Exception handlers can inform users about the status of an application and suggest corrective actions. The type of exception and its message can help generate informative messages for the user.

Silencing Exceptions

Silencing exceptions involves catching exceptions without taking any action, which can be done using an empty except block. This practice is discouraged as it deprives users and developers of information about why an application is malfunctioning. Here are examples of silencing exceptions:

try:
    # some code that might raise an exception
except:
    pass
try:
    # some code that might raise an exception
except Exception:
    pass

The first example catches all exceptions, including system and keyboard events like KeyboardInterrupt. The second example catches a narrower scope of exceptions but is still too broad.

Logging Exceptions

Logging exceptions can provide valuable information for debugging and monitoring applications. Here is an example of using Python's logging module to log an exception:

import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
ch.setFormatter(formatter)
logger.addHandler(ch)
 
try:
    x = 10 / 0
except Exception as e:
    logger.error("something bad happened")

This code sets up a logger that outputs messages to the terminal, formats them, and logs an error when an exception occurs.

FAQ (Frequently asked questions)