Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try...finally...without catch generating an exception

It's a really stupid question but I was wondering something. I have a variable that I have to fill up with an Integer. In some case the source from where I'm getting the data could return an empty string or just be offline. I do not have to handle the offline case because the program will never come this far if the source it's offline. So I thought to do something like this:

    int i = 0;
    try {
        i = mySource.getInt();
    }
    finally {
        System.out.println(i);
    }

int i = 0 is my base value so if I have to parse the empty string I'll just use the initial value. In this case we're gonna generate an exception and it will not be catched. Is there a way to do something like this without handling the exception (so without using catch(Exception e){}) or is it just bad practice?

Just to clarify: I do not need to check if the source is online now because it's a parsed xml file so I'll check if it's offline when I'm downloading the file.

like image 328
dierre Avatar asked Dec 04 '22 20:12

dierre


1 Answers

The exception will propagate if you don't catch it. Since you know what caused the exception, you don't want control flow to be interrupted, and you just want the default value, propagating the exception doesn't do any good. Just catch it and eat it, then use the default value.

The time to use try ... finally with no catch is when you have something that needs cleaning up (a resource that needs closing, usually), but you don't want to handle any exceptions that might get thrown, you want to let them go. This is the opposite case, you don't have anything that needs closing, you just want to squelch the exception and use a default value.

like image 136
Nathan Hughes Avatar answered Dec 21 '22 15:12

Nathan Hughes