When executing a program, errors can occur due to unexpected data input or missing files. In Python, these runtime errors are called “Exceptions.” Normally, when an exception occurs, the program terminates immediately. However, by implementing appropriate “exception handling,” you can prevent the program from crashing, display error messages, and continue processing or exit safely.
This article explains how to implement basic exception handling using the try-except statement.
Risks of Not Handling Exceptions
First, let’s look at a case where an error occurs without exception handling. Consider a function that calculates the unit cost per item from the total cost and quantity.
def calculate_unit_cost(total_cost, quantity):
"""
Divide total_cost by quantity to display unit cost
"""
cost = total_cost / quantity
print(f"Unit Cost: {int(cost)} yen")
# 1. Normal Case
calculate_unit_cost(10000, 20)
# 2. Error Case (Quantity is 0)
# calculate_unit_cost(5000, 0)
Output:
Unit Cost: 500 yen
ZeroDivisionError: division by zero
If you pass 0 for quantity, division is impossible, so a ZeroDivisionError occurs and the program crashes. This could potentially stop the entire system.
Catching Exceptions with try-except
To prevent such situations, we use the try-except statement.
tryblock: Write the code that might raise an error.exceptblock: Write the processing to be performed if an error occurs (recovery, logging).
Syntax:
try:
# Process to execute
except ErrorType:
# Process when error occurs
Corrected Code
Let’s add exception handling to the previous function.
def calculate_unit_cost_safe(total_cost, quantity):
try:
result = total_cost / quantity
print(f"Unit Cost: {int(result)} yen")
except ZeroDivisionError:
print("Error: Quantity cannot be 0. Skipping process.")
# Execution Test
print("--- Case 1: Normal ---")
calculate_unit_cost_safe(10000, 20)
print("\n--- Case 2: Zero Division ---")
calculate_unit_cost_safe(5000, 0)
print("\n--- Processing Continues ---")
Output:
--- Case 1: Normal ---
Unit Cost: 500 yen
--- Case 2: Zero Division ---
Error: Quantity cannot be 0. Skipping process.
--- Processing Continues ---
Even though an error occurred, the program did not crash. After displaying the message in the except block, the subsequent processing (“Processing Continues”) was executed.
Receiving Exception Details (Messages)
If you want to get detailed information about what kind of error occurred, use the as keyword to store the exception object in a variable.
except ZeroDivisionError as e:
print(f"An error occurred: {e}")
Handling Multiple Exceptions
Multiple types of errors can occur within a single process. For example, if non-numeric characters are input, a TypeError or ValueError might occur. By writing multiple except blocks, you can respond differently to each error type.
def robust_calculation(total, count):
try:
# Execute division
unit_price = total / count
print(f"Result: {unit_price}")
except ZeroDivisionError:
# Division by zero
print("Error: Division by zero is invalid.")
except TypeError as e:
# Non-numeric type passed
print(f"Error: Non-numeric data included. Details: {e}")
except Exception as e:
# All other unexpected errors
print(f"Unexpected error occurred: {e}")
# Test
robust_calculation(3000, "5 pieces") # Try passing a string
Output:
Error: Non-numeric data included. Details: unsupported operand type(s) for /: 'int' and 'str'
Since Exception is the parent class of almost all exceptions, putting it last allows you to catch any unforeseen errors (though specifying concrete exception classes is recommended to make debugging easier).
Summary
- In Python, use the
try-exceptstatement to handle runtime errors (exceptions). - Catching exceptions prevents program crashes and allows for appropriate error messages or alternative processing.
- You can get detailed error info with
except ErrorType as variable:. - You can branch processing for each error type by writing multiple
exceptblocks.
