Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to do "try-finally" without "catch"?

Tags:

java

exception

People also ask

Can we use try finally without catch?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.

Is catch necessary for try?

It is not necessary to catch all exceptions. In Java there is two types of exceptions: checked and unchecked. The rule is simple a checked exception has to be handled by the caller while an unchecked exception can be handled either by not catching it, or by catching it.

Should everything be in a try catch?

Exactly. Putting everything in a try/catch statement is usually a sign of an inexperienced developer who doesn't know much about exceptions IME.


This is useful if you want the currently executing method to still throw the exception while allowing resources to be cleaned up appropriately. Below is a concrete example of handling the exception from a calling method.

public void yourOtherMethod() {
    try {
        yourMethod();
    } catch (YourException ex) {
        // handle exception
    }
}    

public void yourMethod() throws YourException {
    try {
        db.store(mydata);
    } finally {
        db.cleanup();
    }
}

It's there because the programmer wanted to make sure that db.cleanup() is called even if the code inside the try block throws an exception. Any exceptions will not be handled by that block, but they'll only be propagated upwards after the finally block is executed. The finally block will also be executed if there was no exception.


Why does this code do it this way?

Because apparently the code doesn’t know how to handle exceptions at this level. That’s fine – as long as one of the callers does, i.e. as long as the exception gets ultimately handled somewhere.

Often, low-level code cannot react appropriately to exceptions because the user needs to be notified, or the exception must be logged, or another strategy has to be tried. Low-level code performs one function only and doesn’t know about higher-level decision making.

But the code still needs to clean up its resources (because if it doesn’t, they would leak), so it does just that in the finally clause, making sure that it always happens, whether an exception was thrown or not.


The finally block ensures that even when a RuntimeException is thrown (maybe due to some bug in the called code), the db.cleanup() call will be made.

This is also often used to prevent too much nesting:

try
{
    if (foo) return false;
    //bla ...
    return true;
}
finally
{
    //clean up
}

Especially when there are many points at which the method returns, this improves readability as anyone can see the clean up code is called in every case.