0

I was wondering if we can execute our code entirely in the try section without using else. Obviously it works. here is an example:

x = int(input())
try:
  print(10/x)
  print("Possible")

except ZeroDivisionError as e:
 print(e)

Or we can do this which is the mostly used syntax:

x = int(input())
try:
  print(10/x)

except ZeroDivisionError as e:
  print(e)

else:
  print("Possible")

We can even use a condition in this case:

x = int(input())

if x !=0:
  print(10/x)
  print("possible")

elif x ==0 :
  print("Error!")

So what is the difference between these three? which one should be used? all three seem to be able to catch and prevent errors.

2 Answers 2

1

Probably the first one. Here's the reason. When you use a try-except block you get the control over the exception and you can display custom messages along with the stack trace. The second one is not very readable and a little redundant (after all why do you want to display any message if everything went fine!) and the third one doesn't show where and how the error occurred. If that is not your concern, any of these would work just fine.

Sign up to request clarification or add additional context in comments.

3 Comments

What if the input was inside try and i wanted to print the division result like print(10/x)? , should this print statement be inside try or inside else?
No. It ideally shouldn't be in there if you don;t want to catch any errors in the input. try-except block only take the part of the code for which you want to do error handling. Here, you don't want to handle any errors occurred while the user inputs something so it shouldn't go in the try-except block
Ok then, lets say we have the input outside the block and we define a variable like result =10/x inside try . Now if i want to print result where should the print statement be? Whithin try (toghether with result = 10/x or separately inside else? Both way seem to work.
1

It is better if try-except is used, because you may not always be able to master all errors. For example, if the user enters a "String" you will still get an error.

You can also catch the error you want with the "except" command. And you can see where the error is.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.