Basil Basil - 1 year ago 68
Python Question

Raise exception for non-int argument in __init__

I want to implement class

so that when I pass non-integer, exception is raised and object is NOT created. The following code raises an exception but in can create a quirky fraction
'hello, world'/0

class Fraction:
def __init__(self, num, den):
num = int(num)
den = int(den)
except ValueError:
print('Passed argument not convertible to int')
self.num = num
self.den = den

The question is, how do I elegantly catch non-integer inputs and 0 denominators?

Totally forgot that I need to raise an exception, not just make
clause. Here's how code looks now

class Fraction:
def __init__(self, num, den):
if not (isinstance(num, int) and isinstance(den, int)):
raise ValueError('Got non-int argument')
if den == 0:
raise ValueError('Got 0 denominator')
self.num = num
self.den = den

Answer Source

In the except block just raise the original exception. To check for zero denominator, just do:

if den == 0:
    raise ValueError("boom")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download