Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use exception handling to resolve this issue?

So I have to consider the following function. If we call it on a non-existing file, we would get an FileNotFoundError exception. Moreover, if we call it on a file that doesn’t contain an integer, we would get an ValueError exception.

def l(name:str) -> int:
    reader = open(name, 'r')
    num = int(reader.read())
    reader.close()
    return num

I have to add try-except clauses to this function so that it returns -1 when the input file is missing and returns 0 when the input file doesn’t contain an integer.

Here is my code so far, which clearly doesn’t work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try:
    def load(filename:str) -> int:
        reader = open(filename, 'r')
        num = int(reader.read())
        reader.close()
        return num
except FileNotFoundError:
    print("-1")
except ValueError:
    print('0')

What changes should I make to ensure that this code works??

>Solution :

The try...except should be inside the function. ie:

def load(filename:str) -> int:
    try:
        reader = open(filename, 'r')
        num = int(reader.read())
        reader.close()
        return num
    except FileNotFoundError:
        return -1
    except ValueError:
        return 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading