Exception Handling
Exception handling allows a program to handle errors gracefully without stopping abruptly. Python uses try...except blocks.
When a program runs, many things can go wrong: the user types letters when a number is requested, a file to read is not found, or a network connection drops. Without exception handling, these errors will forcibly stop the program and display a confusing traceback to the user. With try...except blocks, we can catch specific errors and respond appropriately, such as showing a friendly message or asking for input again.
The else block runs if no exception occurs; it is useful for code that should only be executed when the try block succeeds. The finally block always runs regardless of what happens, making it suitable for cleaning up resources such as closing a file or a database connection. Python also supports creating custom exceptions by inheriting the Exception class, enabling error handling specific to your application's needs.
Common Exceptions:
ValueError— value does not matchTypeError— type does not matchZeroDivisionError— division by zeroFileNotFoundError— file not foundKeyError— key does not exist in dictIndexError— index out of range
Code Example
# try - except - else - finally
try:
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
print("Input is not a number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result: {result}")
finally:
print("Done.")
# Custom Exception
class ScoreError(Exception):
pass
def set_score(n):
if not 0 <= n <= 100:
raise ScoreError("Score must be 0-100")
return n
Code Explanation
The try block contains code that might raise an error: converting the input to an integer and the division. If the user enters text, ValueError is caught by except ValueError. If 0 is entered, ZeroDivisionError is caught. If there is no error, the else block prints the calculation result. The finally block prints "Done." whether it succeeds or fails. For the custom exception, the ScoreError class inherits from Exception, and the set_score() function uses raise to trigger an error if the value is outside the 0-100 range.
Everyday Example
A school's student grade input system needs to validate the data entered by teachers. If a teacher types text when a number is requested, ValueError is caught and the system asks for input again. If the grade is outside the 0-100 range, the custom exception ScoreError gives a specific warning. The system also logs every error to a log file in the finally block for auditing purposes. With exception handling, teachers get clear feedback without the application crashing.
Summary
Exception handling makes programs more robust and user-friendly. The combination of try, except, else, and finally gives full control over error flow, while custom exceptions enable specific business validation.