Exception Handling allows us to handle errors and unexpected situations that may occur during program execution.
Exceptions are raised when an error or exceptional condition occurs during the execution of a program. Python provides a way to handle these exceptions using try-except blocks.
The basic structure of a try-except block is as follows:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
In this structure, the code within the try
block is executed. If an exception of the specified ExceptionType
is raised within the try
block, the program jumps to the corresponding except
block, where we can handle the exception.
Let's see an example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")
In this example, we attempt to divide the number 10 by zero, which raises a ZeroDivisionError
. The program then jumps to the except
block, where we print an error message indicating the division by zero.
We can also raise exceptions manually using the raise
keyword. This is useful when we want to indicate an exceptional condition in our code. Here's an example:
x = -1
if x < 0:
raise ValueError("Invalid value: x must be positive.")
In this example, we raise a ValueError
exception if the value of x
is negative. The ValueError
exception is created with a custom error message that provides information about the exceptional condition.
In addition to the try
and except
blocks, Python provides two optional blocks: else
and finally
.
The else
block is executed only if no exception occurs within the try
block. It is useful for performing actions that should be executed when no errors are encountered.
The finally
block is always executed, regardless of whether an exception occurs or not. It is used for releasing resources or performing cleanup operations that need to be executed regardless of the outcome of the try
block.
Here's an example that demonstrates the usage of try
, except
, else
, and finally
blocks:
try:
x = 10 / 2
except ZeroDivisionError:
print("Error: Division by zero!")
else:
print("The division was successful.")
finally:
print("End of try-except-else-finally block.")
In this example, the division operation within the try
block is successful, so the program executes the else
block and prints a success message. Finally, the program executes the finally
block to signal the end of the entire try-except-else-finally block.