Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

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 

1 Answer

0 votes
by (36.8k points)

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

if den == 0:

    raise ValueError("boom")

Do check out Data Science with Python course which helps you understand from scratch 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...