What is the purpose of else part in python exception handling?

0 votes
I have never found the need to use the else part with try statement. So I just want to know its usage under some conditions.
Aug 22 in Python by Neel
• 3,010 points
12 views

1 answer to this question.

0 votes

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.These exceptions can be handled using the try statement:

Example

The try block will generate an exception because x is not defined:

try:
  print(x)
except:
  print("An exception occurred")

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example

In this example, the try block does not generate any error:

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

An else clause will execute if there were no errors, and by not executing that code in the try block, you avoid catching an unexpected error. Again, catching an unexpected error can hide bugs.

answered Aug 22 by Arvind
• 2,960 points

Related Questions In Python

0 votes
1 answer

What is the purpose of inner class in Python?

Advantages of inner class: Logical grouping of classes: ...READ MORE

answered Feb 7 in Python by SDeb
• 13,160 points
187 views
0 votes
1 answer

What is the purpose of using lambda functions in Python?

The main purpose of anonymous functions come ...READ MORE

answered Jun 11 in Python by Nisa
• 1,090 points
37 views
0 votes
1 answer

What is the purpose of hash function in python?

The hash() method returns the hash value of an object if it ...READ MORE

answered Aug 2 in Python by Mohammad
• 3,060 points
31 views
0 votes
0 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 236 views
+4 votes
6 answers
0 votes
1 answer

What is the use of '==' operator in dictionary in Python?

Yes you can use '==' operator to ...READ MORE

answered Jul 24 in Python by Arvind
• 2,960 points
17 views
0 votes
1 answer

What is the difference between str() and repr() functions in Python?

str() is mostly used to create output ...READ MORE

answered Jul 8 in Python by Arvind
• 2,960 points
72 views