0

I have the following java code :

 public void someMethod(){

    try{

        // some code which generates Exception

    }catch(Exception ex1) {

        try{

                // The code inside this method can also throw some Exception
                myRollBackMethodForUndoingSomeChanges();

        }catch(Exception ex2){
            // I want to add inside `ex2` the history of `ex1` too
            // Surely , I cannot set cause of `ex2` as `ex1` as `ex2`
            // can be caused by it's own reasons.
            // I dont want `ex1` details to be lost if I just throw `ex2` from my method



        }
    }

}

How to do it ?

EDIT : Actually this happens in my service layer and I have controller advice for logging. Hence I don't want to add 2 loggers here.

Number945
  • 4,631
  • 8
  • 45
  • 83
  • Why cant you just throw `ex2`, is there a reason you want to throw `ex1` as well? If really necessary you could add an additional property `rootCause` to `ex2` and initialize it with `ex1` if needed. – Glains Oct 24 '18 at 16:08
  • Don't catch runtime exceptions - they signal that you've done something wrong as a developer. Instead, identify what's causing your code to break at runtime and fix it. See https://stackoverflow.com/questions/3162760/differences-between-runtime-checked-unchecked-error-exception – Michael Peacock Oct 24 '18 at 16:09
  • I have edited the question. – Number945 Oct 24 '18 at 16:12

1 Answers1

5

You can add ex1 to the supressed exceptions in ex2 via the method addSuppressed before rethrowing it.

Quick code example:

public static void main(final String[] args) {
    try {
        throw new IllegalArgumentException("Illegal Argument 1!");
    } catch (final RuntimeException ex1) {
        try {
            throw new IllegalStateException("Illegal State 2!");
        } catch (final RuntimeException ex2) {
            ex2.addSuppressed(ex1);
            throw ex2;
        }
    }
}

will produce the exception output:

Exception in thread "main" java.lang.IllegalStateException: Illegal State 2!
    at package.main(Main.java:26)
    Suppressed: java.lang.IllegalArgumentException: Illegal Argument 1!
        at package.main(Main.java:20)
OH GOD SPIDERS
  • 3,091
  • 2
  • 13
  • 16