In Python, try
, except
, and finally
are used for handling exceptions, which are errors detected during execution. These keywords allow you to gracefully handle errors and execute code regardless of whether an error occurred.
1. try
Block
The try
block lets you test a block of code for errors.
try: # Code that may cause an exception result = 10 / 0 print(result) except ZeroDivisionError: print("You can't divide by zero!")
2. except
Block
The except
block lets you handle the error.
try: # Code that may cause an exception result = 10 / 0 print(result) except ZeroDivisionError: print("You can't divide by zero!")
In this example, the ZeroDivisionError
exception is caught and a message is printed instead of the program crashing.
3. finally
Block
The finally
block lets you execute code, regardless of the result of the try
and except
blocks.
try: # Code that may cause an exception result = 10 / 0 print(result) except ZeroDivisionError: print("You can't divide by zero!") finally: print("This will always be executed.")
Here, the message in the finally
block will be printed no matter if an exception occurred or not.
Combined Example
Here’s a more comprehensive example that combines try
, except
, and finally
:
def divide(a, b): try: result = a / b except ZeroDivisionError: print("Error: Division by zero is not allowed.") result = None finally: print("Execution complete.") return result # Testing the function print(divide(10, 2)) # Expected output: 5.0 print(divide(10, 0)) # Expected output: Error message and None
In this example:
- The
try
block contains the code that may raise an exception. - The
except
block handles the specificZeroDivisionError
exception. - The
finally
block contains code that will always be executed, whether an exception occurs or not.
Multiple Except Blocks
You can also have multiple except
blocks to handle different types of exceptions.
try: value = int(input("Enter a number: ")) result = 10 / value except ValueError: print("Error: Invalid input. Please enter a number.") except ZeroDivisionError: print("Error: Division by zero is not allowed.") finally: print("Execution complete.")
In this case, different exceptions (ValueError
and ZeroDivisionError
) are handled separately, providing more specific error messages.
Using try
, except
, and finally
helps in making your code more robust and error-tolerant.