w3resource

Understanding the else block in Python Try-Except

How does the else block work in a try-except structure? When is it executed?

In a Python "try...except" structure, the "else" block specifies a block of code that should be executed if no exceptions are raised in the "try" block. When no exceptions occur, it provides an alternative path for code execution. The basic syntax is as follows:

try:
    # Code that may raise exceptions
except ExceptionType1:
    # Code to handle ExceptionType1
except ExceptionType2:
    # Code to handle ExceptionType2
# ...
except ExceptionTypeN:
    # Code to handle ExceptionTypeN
else:
    # Code to execute if no exceptions occurred in the try block

In the above syntax,

  1. Python first attempts to execute the code within the "try" block.
  2. If an exception is raised at any point inside the "try" block, Python immediately jumps to the appropriate "except" block based on the type of exception. The code within that "except" block is executed.
  3. If no exceptions occur within the "try" block, the "else" block is executed immediately after the "try" block completes its execution.

Here is an example:

Code:

try:
    n = int(input("Input a number: "))
    result = 10 / n
except ValueError:
    print("Invalid input. Please enter a valid integer.")
except ZeroDivisionError:
    print("Division by zero is not allowed.")
else:
    print(f"Result: {result}")

Output:

Input a number: a
Invalid input. Please enter a valid integer.
 
Input a number: 0
Division by zero is not allowed.
Input a number: 2
Result: 5.0

In the example above, if the user inputs a valid integer and doesn't divide it by zero, the code in the "else" block will execute and print the result. The "else" block will not be executed if an exception occurs.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-interview/how-does-the-else-block-work-in-a-try-except-structure-when-is-it-executed.php