Basil - 2 months ago 13

Python Question

I want to implement class

`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?

Totally forgot that I need to raise an exception, not just make

`except`

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