I am trying t to implement class Fraction so that when I pass non-integer, the exception is raised and the object is NOT created.
The following code raised an exception but it can create a quirky fraction 'hello, the 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
My question is, how do I elegantly catch non-integer inputs and 0 denominators?
I have to Update the 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 TypeError('Got non-int argument')
if den == 0:
raise ValueError('Got 0 denominator')
self.num = num
self.den = den