try…except…else in Python: Improving the Control Flow

In Python, the 'try...except...else' statement is an extended version of the 'try...except' and try…except…finally statement that includes a 'else' block. The 'else' block is executed when there are no exceptions raised within the try block.

The 'else' block is useful when you want to perform specific actions when no exceptions occur. It can be used, for example, to execute additional code if the 'try' block succeeds in its operation and enhances the program flow. You'll understand more about 'try…except…else' in this article as I'll be explaining the syntax and working with an example program in Python.

Syntax of try…except…else in Python:

The syntax of try…except…else is as follows:

 >>> try:
 >>>     # Code that might raise an exception
 >>>     # ...
 >>> except ExceptionType1:
 >>>     # Code to handle ExceptionType1
 >>>     # ...
 >>> except ExceptionType2:
 >>>     # Code to handle ExceptionType2
 >>>     # ...
 >>> else:
 >>>     # Code that always executes, regardless of whether an exception occurred or not
 >>>     # …

Working of try...except…else in Python:

  1. The statements within the 'try' block are executed one by one.
  2. If an exception occurs during the execution of any statement within the 'try' block, the remaining statements within the block are skipped, and the control is transferred to the appropriate 'except' block.
  3. The exception is compared with the specified exception types in the 'except' blocks. If the exception matches any of the exception types listed in the 'except' blocks, the corresponding block is executed.
  4. If no exception occurs in the try block, the code within the 'else' block is executed. This block is optional and provides an opportunity to execute code that should only run when no exceptions are raised.
  5. After executing the 'else' block, the program continues its execution from the next statement after the entire 'try...except...else' statement.

Example Program for try…except…finally in Python:

 >>> def divide_numbers(a, b):
 >>>     try:
 >>>         result = a / b
 >>>         print("Division result:", result)
 >>>     except ZeroDivisionError:
 >>>         print("Error: Division by zero is not allowed.")
 >>>     else:
 >>>         print("Division result:", result)
 >>> # Example usage
 >>> divide_numbers(9, 3)
 >>> divide_numbers(5, 0)

In this example, the 'divide_numbers' function performs division between two numbers. If a 'ZeroDivisionError' occurs, it is caught in the 'except' block, and an error message is printed. Otherwise, if no exception occurs, the code within the 'else' block is executed, printing the division result.

  • In the first call to 'divide_numbers(9, 3)', the division is successful, and the 'else' block is executed. The output will be:
Output:

Division result: 3.0

  • In the second call to 'divide_numbers(5, 0)', a 'ZeroDivisionError' occurs since we're attempting to divide by zero. The exception is caught by the corresponding 'except' block, and an error message is printed. The output will be:
Output:

Error: Division by zero is not allowed.

This example demonstrates how 'try...except...else' allows you to handle exceptions and execute code that should only run when no exceptions occurred, providing more control over the program's flow and enhancing its error handling capabilities.

Conclusion:

In conclusion, the 'try...except...else' statement in Python offers a powerful mechanism for handling exceptions while also executing code that should run only if no exceptions are raised. The 'else' block provides a convenient way to define code that is executed when the 'try' block completes successfully without any exceptions. This allows for more precise control over the program's flow

Hope you understood this concept clearly. If you have any queries regarding this topic, put it down in the comments.


Learn via Video Course

Python Logo

Python

6109

7 hrs