Error handling is a technique for managing and responding to exceptions, which are errors detected during execution of code. Effective error handling ensures that your program can deal with unexpected situations without crashing. This is particularly important in data-driven fields, where the input data might be unpredictable or in an unexpected format.
Syntax
The primary constructs for error handling are try, except, else, and finally:
try: This block lets you test a block of code for errors.
except: This block handles the error or specifies a response to specific error types.
else: (Optional) This block runs if no errors are raised in the try block.
finally: (Optional) This block executes regardless of the result of the try-except blocks.
try:# Code block where exceptions might occurexcept SomeException:# Code to handle the exceptionelse:# Code to execute if no exceptions occur (optional)finally:# Code to execute regardless of exceptions (optional)
In addition to catching exceptions, Python allows programmers to raise their own exceptions using the raise statement. This can be useful for signaling specific error types in a way that is clear and tailored to your program’s needs.
Python also has the isinstance() function that enables easy checking of strict data types. This is a Pythonic and handy method to validate input data types in functions.
Example: Classification of soil acidity-alkalinity
To illustrate these error handling concepts, let’s write a simple function to determine whether a soil is acidic or alkaline based on its soil pH. This fucntion will not only require that we pass a numeric input to the function, but also that the range of soil pH is within 0 and 14.
def test_soil_pH(pH_value):""" Determines if soil is acidic, alkaline, or neutral based on its pH value. Parameters: pH_value (int, float, or str): The pH value of the soil. It should be a number or a string that can be converted to a float. Valid pH values range from 0 to 14. Returns: str: A description of the soil's acidity or alkalinity. Raises: TypeError: If the input is not an int, float, or string. ValueError: If the input is not within the valid pH range (0 to 14). """ifnotisinstance(pH_value, (int, float, str)):raiseTypeError(f"Input type {type(pH_value)} is not valid. Must be int, float, or str.")try: pH_value =float(pH_value)ifnot (0<= pH_value <=14):raiseValueError("pH value must be between 0 and 14.")exceptValueErroras e:returnf"Invalid input: {e}"# Classify the soil based on its pH valueif pH_value <7:return"The soil is acidic."elif pH_value >7:return"The soil is alkaline."else:return"The soil is neutral."# Example usage of the functionprint(test_soil_pH("5.5")) # Acidic soilprint(test_soil_pH(8.2)) # Alkaline soilprint(test_soil_pH("seven")) # Invalid inputprint(test_soil_pH(15)) # Valid input, out of rangeprint(test_soil_pH([7.5])) # Invalid type
The soil is acidic.
The soil is alkaline.
Invalid input: could not convert string to float: 'seven'
Invalid input: pH value must be between 0 and 14.
TypeError: Input type <class 'list'> is not valid. Must be int, float, or str.
Explanation
Data type check with isinstance: At the beginning of the function, we use isinstance() to check if the input is either an int, float, or str. The TypeError message includes the type of the wrong data type to inform the user about the nature of the error.
Conversion and range check: Inside the try block, the function attempts to convert the input to a float and then checks if it’s within the valid pH range, raising a ValueError if it’s out of range.
Handling value error: The except block catches and returns a message for any ValueError.