public class Onion implements AutoCloseable{
public void m1() throws Exception{ throw new Exception("Exception from m1");}
public void m2() throws Exception{
try (Onion o = new Onion()) {o.m1();}
catch(Exception e) { throw e;}
finally{ throw new RuntimeException("Exception from finally");}
}
public static void main(String[] args) {
try (Onion o = new Onion()){o.m2();}
catch(Exception e){
Throwable[] ta = e.getSuppressed();
for(Throwable t : ta)
System.out.println(t.getMessage());
}
}
@Override
public void close() throws Exception {
throw new RuntimeException("Exception from close");
}
and it still only one exception is suppressed -- the one from the close() method.
You can try wrapping this whole code in the close method of another class. That should suppress the exception that you are getting right now, which internally already has one suppressed exception. Haven't tried it myself but you can
If you like our products and services, please help us by posting your review here.
Another option is to generate exceptions yourself in try catch blocks and in the catch blocks, keep adding the exception to other suppressed exception using the addSuppressed(Throwable exception) method.
If you like our products and services, please help us by posting your review here.
public class AddSuppressed {
public static void m1() throws Exception{
throw new Exception("Exception from m1");
}
public static void m2() throws Exception{
Throwable t = null;
try{
m1();
}catch(Exception e){
//Can't do much about this exception so rethrow it
t = e;
}finally{
Exception e = new RuntimeException("Exception from finally");
e.addSuppressed(t);
throw e;
}
}
public static void main(String[] args) {
try{
m2();
}catch(Exception e){
System.out.println(e);
Throwable[] ta = e.getSuppressed();
for(Throwable t : ta) {
System.out.println(t.getMessage());
}
}
}
}
Hi! Can you please explain why in general if we have exception in catch and finally we get just exception from finally and exception from catch is just gone.
A method can throw only one exception, so, as a language designer you have to decide which one you want the method to throw - the one thrown in the catch block or the one thrown in finally. Unless, you want the method to be able to throw multiple exceptions at the same time.
If you like our products and services, please help us by posting your review here.
The first para of the explanation already explains why:
the given code, method m2() throws an exception explicitly from the catch block as well as from the finally block. Since this is an explicit finally block (and not an implicit finally block that is created when you use a try-with-resources statement), the exception thrown by the finally block is the one that is thrown from the method. The exception thrown from the catch block is lost. It is not added to the suppressed exceptions list of the exception thrown from the finally block.
If you like our products and services, please help us by posting your review here.