Basil Basil - 1 month ago 8
Python Question

Raise exception for non-int argument in __init__

I want to implement class

Fraction
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):
try:
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?

Update
Totally forgot that I need to raise an exception, not just make
except
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

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

if den == 0:
    raise ValueError("boom")
Comments