icon: LiWrench
Title: A Gentle Intro to Exception Handling in Python
✦ Exception handling is a fundamental skill for every Python programmer. It allows programmers to handle errors and unexpected situations that can arise during program execution.
✦ In this note, we’ll explore how to handle these unexpected situations in Python.
✦ By the end of this note, you’ll learn how to handle errors without having your application crashes or stops abruptly, making your applications more reliable.
Here is the basic structure of the Exception Handling
# Step 1: Understand the basic structure
try:
# Code that might raise an exception
<..>
except ExceptionType:
# Code to handle the exception
<..>
finally:
# Code to be executed regardless of whether an exception was raised
<..>
Python’s try
and except
statements provide a safety net for your code, allowing you to catch and handle exceptions that might occur during execution. This prevents your program from crashing and provides an opportunity to recover gracefully.
try:
dividend = 10
divisor = 0
result = dividend / divisor
except:
print("Error: Division by zero is not allowed.")
The finally
the block is used in conjunction with try
and except
to define cleanup actions that should be performed, regardless of whether an exception occurs or not.
try:
# Attempt to divide 10 by a variable that may be zero
dividend = 10
divisor = 0
result = dividend / divisor
except:
# Handle the error if the divisor is zero
print("Error: Cannot divide by zero.")
finally:
# This block will execute no matter what
print("Division attempt finished.")
In this scenario, the file is opened, and the content is read. If an exception occurs, it is caught and handled. Regardless of the outcome, the finally block ensures that the file is properly closed, preventing resource leaks.
Python provides a comprehensive set of built-in exceptions to handle a wide range of errors and exceptional conditions that can occur during program execution. These exceptions are organized into a hierarchy, with the base class BaseException
at the top. Here are some commonly used built-in exceptions along with a brief description
These are just a few examples of the many built-in exceptions that Python provides.
Here is the example of when we incorporate these specific Exception type into our earlier code:
try:
dividend = 10
divisor = 0
result = dividend / divisor
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Here is another example.
try:
# Attempt to access a key that may not exist in the dictionary
my_dict = {'a': 1, 'b': 2}
value = my_dict['c']
except KeyError:
# Handle the error if the key 'c' does not exist
print("Error: Key not found in the dictionary.")
finally:
# This block will execute regardless of the previous outcome
print("Key lookup attempt finished.")