I have a simple coding scenario like :
class A
{
public static void main(String[] args)
{
try{
//some exception
}
catch(Exception e)
{
//Again some exception
}
finally
{
System.out.println("Finally executed");
}
}
}
My question:
You can simply handle them following way...
class A
{
public static void main(String excep[])
{
try{
//some exception
}
catch(Exception e)
{
//Again some exception
try {}
catch(Exception e){}
}
finally
{
System.out.println("Finally executed");
try {}
catch(Exception e){}
}
}
}
this is usually done in FileStream closing example as shown below example
FileStream in = new FileStream(f);
finally {
if (input != null) {
try {
in.close();
}catch (IOException exp) {
System.out.println(exp);
}
}
1 and 2) yes, you can do both of these by nesting try blocks or letting the exception get thrown (depending on what the situation requires).
3) it is not bad practice, it is unavoidable
There are a couple of things you should be beware of.
One potential problem is exception-masking. When you throw an exception from a catch or finally block, that will supercede any original exception. If you have some kind of Closeable like an InputStream or JDBC object, where you have to close the resource in a finally block, if you let that exception get thrown then you lose the original exception that would tell you what actually went wrong.
Another thing to consider, for the case where you have an exception thrown in a finally block, is whether you want the exception to get propagated at all. For the JDBC example, once a transaction is already committed then if there's an exception thrown on closing the connection it's irrelevant to the business logic, it's just a nuisance. So a common approach for that kind of thing is to catch the exception in the finally block and log it, but don't rethrow it.
The try-with-resources feature is an attempt to fix exception-masking. If an exception is thrown in a finally block after an exception is thrown in the try, the exception on close is added onto the original exception and you can access it through the Throwable#getSuppressed
method.
try-with-resources also provides a way to avoid nesting of try-finally blocks, you can declare multiple closeables and they will get closed in order, last-in-first-out.
try-with-resources suppression of exceptions thrown on close only works if you have an exception thrown in the try block, otherwise the exception thrown on close gets propagated. This behavior is different from the old pattern of catching and logging anything thrown on close, which prevents the close exception from getting rethrown at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With