Exception Handling in Python
Exception handling in Python allows you to handle errors gracefully and prevent your program from crashing.
Try-Except Block
Use the try
and except
blocks to catch and handle exceptions.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Handling Multiple Exceptions
You can handle multiple exceptions by specifying multiple except
blocks.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
Else Clause
The else
clause is executed if no exceptions occur in the try
block.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Result: {result}")
Finally Block
The finally
block is executed regardless of whether an exception occurs.
try:
file = open("example.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print("File closed.")
Custom Exceptions
You can define custom exceptions by creating a new class that inherits from Exception
.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom error")
except CustomError as e:
print(e)
Exception Chaining
Exception chaining allows you to raise a new exception while preserving the original exception.
try:
result = 10 / 0
except ZeroDivisionError as e:
raise ValueError("Invalid operation") from e
Raising Exceptions
You can raise exceptions manually using the raise
keyword.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
try:
check_age(-5)
except ValueError as e:
print(e)
Next: Decorators