Introduction
Exception handling in Python is a powerful mechanism to manage errors and exceptions that may occur during the execution of a program. It helps in maintaining the normal flow of the program even after an error occurs. By using exception handling, you can handle different types of errors gracefully and provide meaningful error messages to the users.
Python Exception Handling Overview
Exception handling in Python is done using the try, except, else, and finally blocks. It allows you to test a block of code for errors, handle the error, execute code if no error occurred, and execute code regardless of the result.
Key Points:
tryblock: Contains the code that may raise an exception.exceptblock: Contains the code that is executed if an exception occurs.elseblock: Contains the code that is executed if no exception occurs.finallyblock: Contains the code that is always executed, regardless of whether an exception occurs or not.
Basic Syntax
Example
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code that runs if the specified exception occurs
print("You can't divide by zero!")
else:
# Code that runs if no exception occurs
print("Division successful!")
finally:
# Code that always runs
print("Execution completed.")
Output
You can't divide by zero!
Execution completed.
Catching Specific Exceptions
You can catch specific exceptions by specifying the exception type after the except keyword.
Example
try:
# Code that may raise an exception
result = int("abc")
except ValueError:
# Code that runs if a ValueError occurs
print("Invalid literal for int() with base 10.")
Output
Invalid literal for int() with base 10.
Catching Multiple Exceptions
You can catch multiple exceptions by using multiple except blocks.
Example
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code that runs if a ZeroDivisionError occurs
print("You can't divide by zero!")
except ValueError:
# Code that runs if a ValueError occurs
print("Invalid literal for int() with base 10.")
Output
You can't divide by zero!
Catching All Exceptions
You can catch all exceptions by using the Exception class.
Example
try:
# Code that may raise an exception
result = 10 / 0
except Exception as e:
# Code that runs if any exception occurs
print(f"An error occurred: {e}")
Output
An error occurred: division by zero
Using the else Block
The else block runs if no exception occurs.
Example
try:
# Code that may raise an exception
result = 10 / 2
except ZeroDivisionError:
# Code that runs if a ZeroDivisionError occurs
print("You can't divide by zero!")
else:
# Code that runs if no exception occurs
print("Division successful!")
Output
Division successful!
Using the finally Block
The finally block runs regardless of whether an exception occurs or not.
Example
try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code that runs if a ZeroDivisionError occurs
print("You can't divide by zero!")
finally:
# Code that always runs
print("Execution completed.")
Output
You can't divide by zero!
Execution completed.
Raising Exceptions
You can raise exceptions using the raise keyword.
Example
def divide(a, b):
if b == 0:
raise ValueError("The divisor cannot be zero.")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(e)
Output
The divisor cannot be zero.
Custom Exceptions
You can define your own exceptions by creating a new class that inherits from the built-in Exception class.
Example
class CustomError(Exception):
pass
def check_value(value):
if value < 0:
raise CustomError("Negative value not allowed.")
try:
check_value(-10)
except CustomError as e:
print(e)
Output
Negative value not allowed.
Conclusion
Exception handling in Python allows you to manage errors gracefully and ensure the normal flow of your program. By using try, except, else, and finally blocks, you can catch and handle different types of exceptions, raise exceptions when needed, and create custom exceptions to suit your specific needs. Understanding and utilizing exception handling is essential for writing robust and error-resistant Python code.