How to get Exception arguments? - python

I was trying to find a way to do this in python 3.6.5 which is not supported
try:
c=1/0
print (c)
except ZeroDivisionError, args:
print('error dividing by zero', args)
It says this type of syntax is not supported by python 3.6.5
So is there a way to get the arguments of the exception?

How about:
try:
c=1/0
print (c)
except ZeroDivisionError as e:
print('error dividing by zero: ' + str(e.args))
Comma notation is now used to except multiple types of exceptions, and they need to be in parentheses, like:
try:
c = int("hello")
c = 1 / 0
print(c)
except (ZeroDivisionError, ValueError) as e:
print('error: ' + str(e.args))

Related

Exception In Python Doesn't Do Anything

I am beginner to python and I have doubt in one program when using try except part
I try to take input from user and add that number by 1 like if you enter 5 then 6 will be printed but if you enter string then except would come in role and print enter only number
I've written code but except is not working there, code is working like if I enter 5 then 6 gets printed but except statement is not working
Here is the code that I've written
def increment(num):
try:
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = int(input("enter your num: "))
a = increment(n)
print(a)
You would have to change to the following:
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The reason for that is that the exception was raised by the int() functions, because it couldn't convert your input to int. The call to int() was before the increment function. Therefore the exception was unhandled.
You tried converting the input to int before going into the try/except block. If you just put it in the try block it will work.
def increment(num):
try:
num = int(num)
return num + 1
except Exception as e:
print("ufff error occured :", e)
n = input("enter your num: ")
a = increment(n)
print(a)
You have to use the type conversion within the try block so that if num is not a number, the controller would move to expect portion.
The problem here is you are using type conversion outside of try-catch block.
Another point to note, convert e to string as a good practice.
Third point to note,the last line print(a) will itself cause trouble in cases of exception as you have returned nothing from the exception part and directly printed the error. Use a return statement in there else it would return None type and which itself will mess up the flow.
def increment(num):
try:
return int(num) + 1 #Updated Line
except Exception as e:
return "ufff error occurred :" + str(e) #Updated Line
n = input("enter your num: ")
a = increment(n)
print(a)
Might I recommend the following?
def increment(num):
try:
return int(num) + 1
except Exception as e:
print("ufff error occurred:", e)
n = input("enter your num: ")
a = increment(n)
print(a)
The only difference here is that the attempt to convert the user's input to an int occurs within the try-except block, rather than outside. This allows the type conversion error to be caught and your message ("ufff error occurred: ...") to be displayed.
Edit: regarding your comment:
yes it worked out thanks everyone, but can anyone tell what should i have to do if i use int with input line what changes i've to make
Optionally, you could do the following:
def increment(num):
return num + 1
try:
n = int(input("enter your num: "))
a = increment(n)
print(a)
except Exception as e:
print("ufff error occurred:", e)
In this case, I would recommend removing the try-except block in the increment function, because you can safely assume that all values passed to that function will be numeric.
The only code that would raise an exception is the int(...) conversion - and it is not protected under a try/except block. You should put it under the try:
def increment():
try:
return int(input("enter your num: ")) + 1
except ValueError as e:
return f"ufff error occured: {e}"
print(increment())
You should always try to catch the narrowest exception. In this case, a ValueError.

ValueError Exception handling in Python

I want to handle ValueError in Python. But whenever I type the below code I get an error and I want the output as I excepted.
a, b = map(int, input().split())
try:
print(a//b)
except ZeroDivisionError as e:
print('Enter code: ', e)
except ValueError as e:
print('Enter code: ', e)
If my inputs for a and b are '1' and '$' than
Expected output for ValueError: 'Enter code: invalid literal for int() with base 10: $
Your problem is before your try, here a, b = map(int, input().split())
The $ is given to int, this fails and raise the invalid literal for int() with base 10: $ which is pretty explicit
try:
a, b = map(int, input().split())
print(a//b)
except ZeroDivisionError as e:
print('Enter code: ', e)
except ValueError as e:
print('Enter code: ', e)

Continue script execution after try/except exception with Python

Coming from other scripting languages I'm probably missing something fundamental here.
How do I continue on with the rest of the script when an exception is raised?
Example:
errMsg = None
try:
x = 1
y = x.non_existent_method()
except ValueError as e:
errMsg = str(e)
if errMsg:
print('Error')
else:
print('All good')
The script just fails. Is there a way to continue with the rest?
Thanks in advance
It should be Exception and not ValueError:
errMsg = None
try:
x = 1
y = x.non_existent_method()
except Exception as e:
errMsg = str(e)
if errMsg:
print('Error')
else:
print('All good')

How can my program know an exception from a separate method [duplicate]

This question already has answers here:
Manually raising (throwing) an exception in Python
(11 answers)
Closed 3 years ago.
I am writing a python program.
It calls a private method which has try...except... and returns a value.
Such as:
def addOne(x):
try:
a = int(x) + 1
return a
except Exception as e:
print(e)
def main():
x = input("Please enter a number: ")
try:
y = addOne(x)
except:
print("Error when add one!")
main()
The output is this when I entered an invalid input "f"
Please enter a number: f
invalid literal for int() with base 10: 'f'
I want to detect the exception in both main() and addOne(x)
So the ideal output may looks like:
Please enter a number: f
invalid literal for int() with base 10: 'f'
Error when add one!
Could anyone tell me how to do? Thanks!
Handling an exception prevents it from propagating further. To allow handling the exception also in an outer scope, use a bare raise inside the exception handler:
def addOne(x):
try:
a = int(x) + 1
return a
except Exception as e:
print(e)
raise # re-raise the current exception

Bypassing ZeroDivisionError

How can I bypass the ZeroDivisionError and allow the program to continue whilst noting the 0 value?
for line in data:
split=line.split()
ptot=0
ntot=0
for pchar in "HKR":
pchartotal=split[1].count(pchar)
#print pchartotal
ptot+=pchartotal
for nchar in "DE":
nchartotal=split[1].count(nchar)
#print nchartotal
ntot+=nchartotal
print float(ptot)/float(ntot)
change this:
print float(ptot)/float(ntot)
to
try:
print float(ptot)/float(ntot)
except ZeroDivisionError as err:
print err
you can use try-except :
for line in data:
split=line.split()
ptot=0
ntot=0
for pchar in "HKR":
pchartotal=split[1].count(pchar)
#print pchartotal
ptot+=pchartotal
for nchar in "DE":
nchartotal=split[1].count(nchar)
#print nchartotal
ntot+=nchartotal
try:
print float(ptot)/float(ntot)
except ZeroDivisionError :
print "ZeroDivisionError: integer division or modulo by zero"
You can use try{..} except{..} block
try:
print float(ptot)/float(ntot)
except ZeroDivisionError:
print 'divide by zero'
Handling Exceptions
Try:
try:
print (1/0)
except ZeroDivisionError:
print ("Yo that's divide by zero")
print ("Done cya")
Or you could just test and substitute the value when detecting a zero divisor;
print ('NA' if not ntot else float(ptot)/float(ntot))

Categories