Module 10 - Exception Handling Header

Module 10 - Exception Handling

Introducing Exception Handling

try and except:

Exception handling is a crucial aspect of writing robust and reliable code. It allows you to gracefully handle and recover from runtime errors or exceptional situations that may occur during program execution. Without it, as you may have already discovered, the Python program will crash (stop running) when it encounters all kinds of errors.  Python provides the try and except statements to implement exception handling.

The general structure of a try and except block in Python is as follows:

try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception

The try block encloses the code that might raise an exception. If an exception occurs within the try block, it is caught by the corresponding except block. The except block specifies the type of exception it can handle. You can have multiple except blocks to handle different types of exceptions.

Notice that in the try and except block, the code is indented as with loops and if…else statements.

else:

The else block is an optional block that follows the try-except block. It is executed only if no exception occurs in the try block. It allows you to specify code that should run when the try block executes successfully.

Example:

try:
result = 10 / 2 # No exception
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Result:", result)

In this example, since no exception occurs during the division, the code in the else block is executed, printing the result.

finally:

The finally block is an optional block that follows the try-except or try-except-else blocks. It is executed regardless of whether an exception occurs or not. It is typically used to define cleanup code that must be executed, such as closing files or releasing resources.

Example:

try:
file = open("data.txt", "r")
# Code to read the file
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close() # Close the file regardless of exception occurrence

In this example, the finally block ensures that the file is closed, even if an exception occurs while reading the file.

raise:

The raise statement is used to manually raise an exception in Python. It allows you to create custom exceptions or handle exceptional cases that may not be caught by existing exception types.

Example:

def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
elif age > 120:
raise ValueError("Invalid age.")
else:
print("Valid age.")

try:
validate_age(150)
except ValueError as ve:
print("Error:", str(ve))
 

In this example, the validate_age function raises a ValueError if the age is negative or exceeds 120. The corresponding except block catches the exception and prints an error message.

These are the main statements associated with try and except in Python. Understanding their usage and knowing when to use each statement is essential for effective exception handling in your programs.



Two Strategies for Exception Handling

Introducing Data Validation:

Data validation is the process of ensuring that data meets specific requirements or constraints before using it in a program. It helps prevent errors and ensures the correctness and integrity of the data.

There are two common strategies for data validation:

  1. Look Before You Leap (LBYL): This strategy involves checking the validity of data before performing an operation. It typically uses conditional statements or boolean expressions to validate the data upfront. LBYL follows the principle of "checking first" to avoid potential errors.
  2. Easier to Ask for Forgiveness than Permission (EAFP): This strategy assumes that valid data will be provided, and errors will be handled through exception handling. EAFP follows the principle of "trying first" and relying on exception handling to address exceptional situations.

Combining LBYL and EAFP:

In practice, a combination of both strategies is often used to achieve comprehensive data validation and exception handling.

First, use LBYL techniques, such as conditional statements, to check for simple and straightforward validation conditions. These conditions could include checking data types, range bounds, or basic formatting requirements.

Next, rely on EAFP techniques, using try and except blocks, to handle more complex validation scenarios or situations where LBYL checks may not be sufficient. Exception handling allows you to catch and handle unexpected errors or exceptional cases that could not be anticipated with LBYL checks alone.

Example:

Let's consider an example where we have to divide two numbers entered by the user. We'll use a combination of LBYL and EAFP techniques to handle data validation and exception handling:

def divide_numbers():
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))

if denominator == 0:
raise ValueError("Denominator cannot be zero.")

result = numerator / denominator
print("Result:", result)
except ValueError as ve:
print("Value Error:", str(ve))
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except Exception as e:
print("An error occurred:", str(e))

# Testing the divide_numbers function
divide_numbers()
 


In this example:

  • We use LBYL techniques by checking if the denominator is zero before performing the division.
  • If the denominator is zero, we raise a ValueError using the raise statement.
  • We use EAFP techniques by using try and except blocks to handle potential exceptions, such as ValueError (raised by us) and ZeroDivisionError (raised by the division operation).
  • If any other unexpected exception occurs, the final except block catches and handles it.
  • By combining LBYL and EAFP strategies, we ensure that the data is validated and exceptions are handled appropriately, providing a more robust and reliable program.

Remember, it's important to choose the appropriate strategy based on the specific data validation requirements and potential exceptions that may occur in your program.

Videos for Module 10 - Exception Handling

Introduction to Error Handling (2:46)

Two Approaches to Error Handling (:56)

The Look Before You Leap Approach to Error Handling (5:19)

The Easier to Ask Forgiveness Approach to Error Handling (4:28)

Catching Named Errors (5:37)

Advanced Try and Except (2:12)

A10 Code Walkthrough and Example (18:31)

Key Terms for Module 10 - Exception Handling

No terms have been published for this module.

Quiz Yourself - Module 10 - Exception Handling

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question