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 23, 2019 in Python by Neel
• 3,020 points
2,042 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 23, 2019 by Arvind
• 3,050 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,300 points
2,315 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
1,708 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,230 points
944 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, 2020 in Python by Gitika
• 65,770 points
11,202 views
0 votes
2 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,443 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,078 views
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
• 3,050 points
723 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
• 3,050 points
1,621 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP