Bypassing ZeroDivisionError - python

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))

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.

How can I show just the 'error' without the 'print pay' statement at the end?

Hello if i run this code and type letters in the input i get the error message but it also shows 'Pay none' I imagine it's because of the order? How can i get it so it just shows the 'Error' message? Thank you
def computepay():
hrs=input('Hours:\n')
rte=input('rte:\n')
try:
h=float(hrs)
r=float(rte)
if h>40:
xp=((h-40)*(1.5*r))
txp=xp+(40*r)
return (txp)
else:
p=h*r
return (p)
except:
print ('Error')
print ('Pay',computepay())
If you don't need the print() statement when it throws an error then try exiting the code on the except block using sys.exit()
import sys
def computepay():
hrs=input('Hours:\n')
rte=input('rte:\n')
try:
h=float(hrs)
r=float(rte)
if h>40:
xp=((h-40)*(1.5*r))
txp=xp+(40*r)
return (txp)
else:
p=h*r
return (p)
except:
print ('Error')
sys.exit(0)
print ('Pay',computepay())
Output:
Hours:
a
rte:
b
Error

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')

Catching ZeroDivisionError

In my exception handling, I'm trying to catch ZeroDivisionError's but for some reason, the code is still doing the division by 0 and not bringing back an error. I must be doing something wrong but I can't seem to place it.
I have tried to move the division elsewhere in the function, and move the division error catch as well.
filename = "numbers.txt"
def main():
total = 0.0
number = 0.0
counter = 0
average = 0
#Open the numbers.txt file
try:
infile = open(filename, 'r')
#Read the values from the file
for line in infile:
counter = counter + 1
number = float(line)
total += number
average = total / counter
#Close the file
infile.close()
except IOError:
print('An error occurred trying to read the file', end=' ')
print(filename, '.', sep='')
except ValueError:
print('Non-numeric data found in the file', end=' ')
print(filename, '.', sep='')
except Exception as err:
print('A general exception occurred.')
print(err)
except ZeroDivisionError:
print('Cannot devide by zero.')
else:
print('Average:', average)
print('Processing Complete. No errors detected.')
# Call the main function.
main()
I'm expecting the result to return the error message when dividing by zero, but it's returning zero as the answer instead.
You need to change the order that you catch exceptions. Since all exceptions in Python inherit from the Exception base class, you are never getting the ZeroDivision exception since it is caught by handling of Exception. Try this:
except IOError:
print('An error occurred trying to read the file', end=' ')
print(filename, '.', sep='')
except ValueError:
print('Non-numeric data found in the file', end=' ')
print(filename, '.', sep='')
except ZeroDivisionError:
print('Cannot devide by zero.')
except Exception as err:
print('A general exception occurred.')
print(err)
else:
print('Average:', average)
print('Processing Complete. No errors detected.')
It seems like there is no ZeroDivisionError in your file. Because in your for loop, you have incremented counter variable by 1 already. Unless, the for loop is iterating into an empty object.
Hence, your average = total / counter will always start as:
average = total / 1 (since counter = counter + 1)
Hope it helped.

How to get Exception arguments?

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))

Categories