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 exception
Example: 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
else
Block: The code inside theelse
block will execute if no exception occurs in thetry
block.finally
Block: The code inside thefinally
block will always execute, regardless of whether an exception occurred or not.
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)