Exceptions in Python
Exceptions are errors that occur during the execution of a program. When an exception occurs, it disrupts the normal flow of the program and can cause it to terminate abruptly. Python provides a built-in mechanism for handling exceptions, allowing you to gracefully recover from errors and continue program execution.
try and except
The try
and except
statements are used to catch and handle exceptions. The code that might raise an exception is placed inside the try
block, and the exception handling code is placed inside the except
block.
try:
x = int(input("Enter a number: "))
result = 10 / x
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero")
except ValueError:
print("Error: Invalid input")
else and finally
The else
clause can be used in conjunction with the try
and except
statements. The code inside the else
block is executed if no exceptions occur in the try
block.
The finally
clause is used to specify a block of code that will be executed regardless of whether an exception occurred or not. This is typically used for cleanup operations, such as closing files or releasing resources.
try:
file = open("data.txt", "r")
contents = file.read()
print(contents)
except FileNotFoundError:
print("Error: File not found")
else:
print("File read successfully")
finally:
file.close()
print("File closed")
Raising Exceptions
Sometimes, you may need to raise an exception explicitly in your code. This can be done using the raise
statement, followed by an exception object.
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
print(result)
except ZeroDivisionError as e:
print(e)
User-defined Exceptions
Python allows you to create your own custom exceptions by defining new exception classes. These user-defined exceptions should inherit from the built-in Exception
class or one of its subclasses.
class InvalidAgeError(Exception):
pass
def validate_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative")
elif age > 120:
raise InvalidAgeError("Age is unrealistically high")
try:
validate_age(-5)
except InvalidAgeError as e:
print(e)
In the next chapter, we'll explore Python collections, such as lists, tuples, dictionaries, and sets, which are powerful data structures for storing and manipulating data efficiently.