Python provides the try
, except
, finally
constructs to facilitate exception handling. These blocks allow programmers to capture errors, handle them gracefully, and ensure certain operations are always carried out, regardless of errors.
try
BlockThe primary objective of the try
block is to execute code that might produce an exception. By placing this potentially problematic code inside a try
block, we prepare ourselves to handle the error if it occurs.
Example:
try:
result = 5 / 0
except:
print("An error occurred.")
except
BlockWhen an exception occurs within the try
block, the code inside the except
block is executed. This block can catch specific exceptions or a generic exception.
Example:
Handling a specific exception:
try:
result = 5 / 0
except ZeroDivisionError:
print("Division by zero!")
Handling multiple exceptions:
try:
# some code that might raise various exceptions
number = int("invalid")
except (ZeroDivisionError, ValueError) as e:
print(f"Caught an error: {e}")
Using multiple except
blocks:
try:
# some code
except ZeroDivisionError:
print("Division by zero!")
except ValueError:
print("Invalid value!")
else
BlockThe else
block, if present, is executed after the try
block code successfully runs without any exceptions. It’s a good place to keep code that you want to execute if no exceptions are raised.
Example:
try:
number = int("5")
except ValueError:
print("Conversion failed.")
else:
print(f"Conversion successful. Number is {number}.")
finally
BlockThe finally
block will always be executed, regardless of whether an exception was raised in the try
block. It’s commonly used for cleanup actions, like closing files or releasing resources.
Example:
try:
file = open("sample.txt", "r")
# some file operations
except FileNotFoundError:
print("File not found.")
finally:
file.close()
print("File closed.")
raise
Sometimes, you might want to raise an exception explicitly, based on certain conditions. The raise
keyword lets you trigger exceptions in your code.
Example:
age = -1
if age < 0:
raise ValueError("Age cannot be negative.")
Another mechanism for raising exceptions is using the assert
statement. It’s a debugging aid that tests a condition. If the condition is True
, it does nothing, but if it’s False
, it raises an AssertionError
with an optional error message.
Example:
age = -1
assert age >= 0, "Age cannot be negative."
try
, except
, finally
, and the associated constructs offer a comprehensive mechanism to deal with exceptions in Python. They ensure that we can write code that’s resilient to unforeseen errors, thereby improving the stability and reliability of our applications. Proper use of these constructs is fundamental in creating user-friendly and robust software solutions.