Home > Net >  How can I use exception handling to resolve this issue?
How can I use exception handling to resolve this issue?

Time:12-02

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.

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

CodePudding user response:

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
  • Related