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, 2019 in Python by Neel
• 3,010 points
104 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, 2019 by Arvind
• 2,980 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, 2019 in Python by SDeb
• 13,250 points
645 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, 2019 in Python by Nisa
• 1,090 points
140 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, 2019 in Python by Mohammad
• 3,210 points
94 views
0 votes
1 answer

What is the purpose of ​#!/usr/bin/python​on the first line in the above code?

Hey, @Roshni, By specifying #!/usr/bin/python you specify exactly ...READ MORE

answered Jun 23 in Python by Gitika
• 33,450 points
27 views
+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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,192 views
0 votes
0 answers
+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, 2019 in Python by Arvind
• 2,980 points
52 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, 2019 in Python by Arvind
• 2,980 points
532 views