![]() |
VOOZH | about |
Finally keyword is used with try and except blocks to define code that always executes, whether an exception occurs or not. It is commonly used for cleanup tasks such as closing files or releasing resources.
Example:
Caught division by zero error. This block always executes.
Important Points
try:
# Code that may raise an exception
except ExceptionType:
# Code that handles the exception
finally:
# Code that always executes
This example demonstrates the finally block executing after an exception is raised and handled.
Can't divide by zero This is always executed
Explanation: The ZeroDivisionError is caught in the except block, printing a message. Regardless of the exception, the finally block executes, ensuring that the cleanup or final statement runs.
This example shows that the finally block executes even when no exception occurs.
5 This is always executed
Explanation: The try block executes without any errors, so the except block is skipped. However, the finally block still runs, demonstrating its unconditional execution.
In this example, the exception is not caught, but the finally block still executes.
Explanation: The division by zero causes a ZeroDivisionError, which is not handled. Despite this, the finally block executes before the program terminates with an error.
This example shows that the finally block executes before the return statement.
Inside try Block Inside Finally 1
Explanation: Although the try block has a return statement, the finally block executes before the function returns the value. This demonstrates that the finally block executes before the function returns a value.