Exception handling is an essential aspect of writing robust and error-tolerant Python code. It allows you to gracefully handle unexpected situations and prevent your program from crashing. Here are the key elements of exception handling in Python:
1. Try-Except Blocks:
- Use
try
andexcept
blocks to handle exceptions. - Code inside the
try
block is executed, and if an exception occurs, it is caught and handled by the correspondingexcept
block.
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError as e:
# Handle the specific exception
print(f"Error: {e}")
2. Multiple Except Blocks:
- You can handle different exceptions with multiple
except
blocks.
try:
# Code that might raise an exception
value = int("string")
except ValueError as e:
print(f"ValueError: {e}")
except TypeError as e:
print(f"TypeError: {e}")
3. Generic Except Block:
- You can use a generic
except
block to catch any unexpected exception.
try:
# Code that might raise an exception
result = 10 / 0
except Exception as e:
# Handle any exception
print(f"Error: {e}")
4. Else Block:
- The
else
block is executed if no exceptions are raised in thetry
block.
try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
else:
print(f"Result: {result}")
5. Finally Block:
- The
finally
block is executed regardless of whether an exception occurs or not. It’s often used for cleanup operations.
try:
# Code that might raise an exception
result = 10 / 2
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("Finally block: This will always execute.")
6. Custom Exceptions:
- You can create your own custom exceptions by defining a new class that inherits from the
Exception
class. “`python
class CustomError(Exception):
pass try:
raise CustomError(“This is a custom exception.”)
except CustomError as e:
print(f”Custom Error: