Exception Handling

What Is an Exception?

An exception is a value (object) that is raised (“thrown”) signaling that an unexpected, or “exceptional,” situation has occurred. Python contains a predefined set of exceptions referred to as standard exceptions.

The standard exceptions are defined within the exceptions module of the Python Standard Library, which is automatically imported into Python programs.

Some standard exceptions in Python include:

The Propagation of Raised Exceptions

An exception is either handled by the client code, or automatically propagated back to the client’s calling code, and so on, until handled. If an exception is thrown all the way back to the main module (and not handled), the program terminates displaying the details of the exception.

Example Scenario:

  • Suppose we have a function validate_password that checks the validity of a password. This function might need to verify the password against a password file. If the password is invalid, it raises an exception.
  • The validate_password function is called by another function, say process_login, which handles user login.

Catching and Handling Exceptions

  • Functions in Python's Standard Library may raise exceptions when encountering errors.
  • For instance, attempting to divide by zero raises a ZeroDivisionError.
  • Example: Handling Exceptions:
    • Without exception handling, division by zero would cause the program to terminate with an error.
    • A try block allows us to catch exceptions raised within the block and handle them gracefully.

Example

# Program to add two numbers with exception handling
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 + num2
print(f"The sum of {num1} and {num2} is {result}.")
except ValueError:
print("Error: Please enter valid integers.")
except Exception as error:
print(f"An error occurred: {error}")

In this program:

  • We ask the user to input two numbers.
  • We attempt to add the numbers within a try block.
  • If the input is not a valid integer, a ValueError is raised.
  • If any other error occurs, it is caught and displayed to the user.
  • This program ensures that even if the user inputs invalid data, the program continues to execute gracefully.

Recovering from Exceptions:

  • Rather than terminating the program, we can prompt the user to enter valid inputs, allowing the program to continue execution.
  • This approach ensures a more user-friendly experience and prevents abrupt program termination.