Exception handling in Python is a powerful feature that enables a program to manage and recover gracefully from unexpected situations or errors that might occur during program execution. Exception handling provides a mechanism to intercept and manage exceptions, preventing the abrupt termination of the program and ensuring robust error handling.
Python's exception handling revolves mainly around four key components: try block, except block, finally block, and raise statement.
1. Try Block:
A try block is used to wrap the segment of code that might cause an exception. If an exception occurs within the block, the control gets passed to the subsequent except block.
Syntax:
try:
# Code that might raise an exception.
except ExceptionType1:
# Handle ExceptionType1.
except ExceptionType2:
# Handle ExceptionType2.
In this structure, if an exception is raised within the try block, control shifts to the except block corresponding to that exception type.
2. Except Block:
The except block is used to capture and handle specific exceptions that might be thrown within the try block.
Syntax:
except ExceptionType as ex:
# Handle the exception.
This block is placed after the try block and handles exceptions of the specified type.
3. Finally Block:
The finally block contains code that always executes, regardless of whether an exception was raised in the try block or not. It's often used for cleanup operations, such as closing open files or releasing resources.
Syntax:
finally:
# Code to be executed always.
4. Raise Statement:
In Python, exceptions can be explicitly triggered using the raise statement. This is particularly useful for raising custom exceptions.
Syntax:
raise ExceptionType("Error message")
Here's an example that demonstrates the use of exception handling in Python:
try:
number = int(input("Enter an integer: "))
if number < 0:
raise ValueError("Negative number entered")
print("You entered", number)
except ValueError as ex:
print("Exception caught:", ex)
finally:
print("Finished processing input.")
In this example, the user is asked to enter an integer. If the entered number is negative, a 'ValueError' exception is raised.