Back

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

In Python the try statement supports an else clause, which executes if the code in try block does not raise an exception. For example:

try:

  f = open('foo', 'r')

except IOError as e:

  error_log.write('Unable to open foo : %s\n' % e)

else:

  data = f.read()

  f.close()

Why is the else clause needed? Can't we write the above code as follows :

try:

  f = open('foo', 'r')

  data = f.read()

  f.close()

except IOError as e:

  error_log.write('Unable to open foo : %s\n' % e)

Won't the execution proceed to data = f.read() if open does not raise an exception?

1 Answer

0 votes
by (25.1k points)

else is used for code that must be executed if the try clause does not raise an exception.

Using else is better than an additional try clause because else avoids accidentally catching an exception that wasn't raised by the code protected by the  try except statement.

Related questions

0 votes
1 answer
asked Jul 4, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
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.2k users

Browse Categories

...