简体   繁体   中英

Exception supposedly never thrown even though it does at runtime

I'm trying to write a small program where I came to the following problem:

In one of my methods I have the following piece of code

try{
    rootHuman = Human.load(scanner.next());
}catch(FileNotFoundException f){
    //Missing Code              
}

where I try to catch a FileNotFoundException. So looking at the function call from Human.load() we have this piece of code

public static Human load(String filename){
    try{
        Human human;
        FileInputStream fileIn = new FileInputStream(filename);
        ObjectInputStream in = new ObjectInputStream(fileIn);
        human = (Human) in.readObject();
        in.close();
        fileIn.close();
        return human;
    }catch(IOException i){
        i.printStackTrace();
        return null;
    }catch(ClassNotFoundException c){
        c.printStackTrace();
        return null;
}

also when trying to catch the FileNotFoundException here I get the same problem. My Problem is that the compiler tells me that this exception is never thrown, but when I execute the code I can obviously get a FileNotFoundException when the input from scanner.next() is a filename that doesn't exist. I'm kind of pointless here so any piece of advice is very much welcome.

Thanks in advance

Your compiler complains about this:

try{
    rootHuman = Human.load(scanner.next());
}catch(FileNotFoundException f){
    //Missing Code              
}

In your Human.load method you catch a IOException , so a FileNotFoundException (witch is actually a sub-type of IOException) will never be thrown in method "load", this catch clausule will always handle it.

Remove the try catch block when calling Human.load() :

 rootHuman = Human.load(scanner.next());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM