Error handling is an essential part of writing robust programs. Python provides a way to handle errors and exceptions using the try...except statement. This lesson will introduce you to the basics of using try...except to manage exceptions in your code.
What is Exception Handling?
Exception handling allows a program to deal with errors gracefully. When an error occurs, Python generates an exception. If not handled, the program will crash. The try...except statement lets you catch and handle exceptions, allowing your program to continue running or handle the error appropriately.
The try...except Statement
The try...except statement consists of a try block and one or more except blocks. The code that might raise an exception is placed in the try block, and the code to handle the exception is placed in the except block.
Python Try…Except Syntax
try:
# Code that may raise an exception
except SomeException:
# Code to handle the exceptionExample: Handling Division by Zero
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")Handling Multiple Exceptions
You can handle multiple exceptions by providing multiple except blocks.
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except TypeError:
print("Error: Invalid data type.")Using the else and finally Blocks
elseBlock: The code inside theelseblock will execute if no exception occurs in thetryblock.finallyBlock: The code inside thefinallyblock will always execute, regardless of whether an exception occurred or not.
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero!")
else:
print(f"Division successful! Result = {result}")
finally:
print("Execution of divide_numbers is complete.")
# Test the function with valid input
divide_numbers(10, 2)
print("\n")
# Test the function with zero division
divide_numbers(10, 0)Raising Exceptions
You can raise exceptions using the raise statement.
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
return True
try:
check_age(15)
except ValueError as ve:
print(ve)

