7.1 try, except, else, finally
Handling errors with try, except, else, and finally blocks to write robust and reliable code.
Exception handling is a fundamental programming technique that allows a program to manage unexpected errors during its execution without crashing. An exception is a signal that something has gone wrong. The primary mechanism for handling these signals in Python is the `try...except` structure.
The try...except...else...finally Structure
- try: This is where you place the "risky" code, i.e., the code that might raise an exception. Python "tries" to execute it.
- except: If an error occurs during the execution of the `try` block, Python immediately stops executing the `try` block and looks for an `except` block that matches the error type. If found, the code in the `except` block is executed. This block is called the "exception handler."
- else (Optional): This block is executed only if the `try` block completes successfully, without any exception being raised. It is useful for code that depends on the successful execution of the `try` block.
- finally (Optional): This block is always executed, regardless of what happened. Whether the `try` succeeded, an exception occurred, or the `else` block was executed, the code in the `finally` block will be executed at the end. It is ideal for "cleaning up" resources (like closing files or network connections), ensuring this action is always performed.
# Example: Handling division by zero and invalid input
# To test different scenarios, change the values:
# num1_str = "10"; num2_str = "2" # Success
# num1_str = "10"; num2_str = "0" # ZeroDivisionError
# num1_str = "abc"; num2_str = "2" # ValueError
try:
num1_str = "10"
num2_str = "2"
number1 = float(num1_str)
number2 = float(num2_str)
result = number1 / number2
except ValueError:
print("Error: Please enter valid numbers.")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
else:
print(f"The result of the division is: {result}")
finally:
print("The division attempt is complete.")
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.