简体   繁体   中英

Skip execution if exception thrown

I am stuck on something very basic. In our game we have a leveleditor/loader that can fetch levels via URL. Now if the URL points to a nonexistant file the editor should refuse to load the level and simply stay in its currentlevel, I am just struggling with the basic code.

private void loadLevel(URL url) {
    Scanner in = null;
    try {
        in = new Scanner(new BufferedReader(new InputStreamReader(
                url.openStream())));
        readLine(in);
        in.close();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Essentially, if FileNotFound is thrown (or any other) readLine(in) should NOT proceed. All kinds of NPE if it does.

private void loadLevel(URL url) {
    Scanner in = null;
    try {
        in = new Scanner(new BufferedReader(new InputStreamReader(
                url.openStream())));
        /*if(in!=null){
            readLine(in);
            in.close();
        }*/
        readLine(in);
        in.close();
    }
    catch (Exception e) { 
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

EDIT: After @LuiggiMendoza's suggestion.

Use throws and finally . Let the calling function handle it. I haven't tested it, but this sort of thing is the idea...

private void loadLevel(URL url) throws IOException, FileNotFoundException {
    Scanner in = null;
    try {
        in = new Scanner(new BufferedReader(new InputStreamReader(
                url.openStream())));
        if (in == null) throw new FileNotFoundException();
        readLine(in);
    }
    finally {
        in.close();
    }
}

On the context of one single thread, if this line below throws exception, the next line of code will not execute. If you think your code is doing otherwise, it might be another thread doing it / some other code

in = new Scanner(new BufferedReader(new InputStreamReader(
            url.openStream())));

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