Reputation: 33
1I'm learning python and finding it difficult to undestand where to place the try and except statement
def divide (n1, n2):
try:
d = n1/n2
except :
print("Wrong")
Then divide (10,0) produces the correct "Wrong"
However if i put the try at the top of the function, it doesn't work
try:
def divide (n1, n2):
d = n1/n2
except :
print("Wrong")
Then divide(10,0) produces the regular traceback error.
Why doesn't the except work in the second example?
Upvotes: 1
Views: 781
Reputation: 11
As the function definition is in the try... except block and not the function call. And always the function definition will not get executed unless it's called (function call should always be in try...except). Hence the second code you mentioned is not efficient enough to catch the exception.
Below piece of code would also work :
def divide (n1, n2):
d = n1/n2
try:
divide(12, 0)
except:
print("Wrong")
Upvotes: 1
Reputation: 406
The first example is the right way to use it.
In the second one, you are defining the function:
def divide (n1, n2):
d = n1/n2
So, when you call it, the try statement is not even executed. The try and except statements are outside the scope, and just useless in the way you want to use them. In this example, the "Wrong" output would be printed just if, when reaching the try, the devide function could not be defined, which is not the case
Here you will find the documentation of how to handle errors and exceptions in Python.
Upvotes: 1
Reputation: 1
in python Try Except will be execute or run if what your execute result error. which is in your example 2 you use def(fucntion) and def in python will not be execute before there call, so that why the except don't work
Upvotes: 0
Reputation: 2882
Your second try-catch only includes how you define the function, and your def
has no exception to raise. And if you call this somewhere: divide(10, 0)
, it's already outside of try-catch block.
Upvotes: 1
Reputation: 71570
It's because if you don't run the function in the try-except section, it always goes through, since a function will always work without being called, if you call it inside the try-except, it will work:
try:
def divide (n1, n2):
d = n1/n2
print(divide(0,0))
except :
print("Wrong")
It will give:
Wrong
But of all solutions, you #1 solution is the best.
Upvotes: 2