Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

What is the intended use of the optional else clause of the try statement?

1 Answer

0 votes
by (106k points)

When we deal with exception handling and in the try block, the statements in the else block are executed if execution falls off the bottom of the try - if there was no exception. 

So, following are some important note that will be useful at the time of dealing with  Exceptions Handling:-

It is better to use the else clause than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

For example, you want to catch exceptions that is raised by throwing an IOError exception, but there's something else you want to do if the first operation succeeds, and you don't want to catch an IOError from that operation, you might write something like this:

try: 

   operation_that_can_throw_ioerror() 

except IOError:

   handle_the_exception_somehow()

else:

  # we don't want to catch the IOError if it's raised     another_operation_that_can_throw_ioerror()

finally:

   something_we_always_need_to_do()

If you just need to put another_operation_that_can_throw_ioerror() after operation_that_can_throw_ioerror, the except would catch the second call's errors. And if you put it after the whole try block, it'll always run, and not until after the finally

The else lets you make sure:-

  1. The second operation will run only if there's no exception.

  2. The second operation will always run before the finally block.

  3. If any IOErrors raised by the second operation then they aren't caught here.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...