Java thrown exception

Let's assume we have the following method (a very simplified version):

    void doSomething() {
      try {
        throw new Exception("A");
      } finally {
        throw new Exception("B");
      }
    }

      

The exception with the message "B" hits the caller method. Basically, is there any way to find out which exception was thrown in the try block if finally the block also throws some kind of exception? Let's assume that the doSomething () method cannot be changed.

+3


source to share


3 answers


JLS section 14.20.2 states:

If the try block terminates abruptly due to the ejection of V, ...

...



If the finally block ends abruptly for the S mind, then the try statement completes abruptly for the S mind (and the throw of the V value will be discarded and forgotten).

Java should throw the original exception V

("finished abruptly") and the entire try-finally block "finishes abruptly" with S

( finally

Exception

, "B").

Unable to retrieve original try

"A" block exception that matches V

in JLS.

+6


source


Block

finally will consume any return values ​​or exceptions from try-catch blocks.



In principle, the final provisions are to ensure proper release of the resource. However, if an exception is thrown inside a finally block, it will consume any return values ​​or exceptions from the try-catch blocks.

0


source


You can do it manually, but it's a bit of a PITA.

public class ExceptionException
{

   public static void main( String[] args )
           throws Exception
   {
      Exception saved = null;
      try {
         throw new Exception( "A" );
      } catch( Exception ex ) {
         saved = ex;
      } finally {
         try {
            throw new Exception( "B" );
         } catch( Exception ex ) {
            if( saved != null )
               ex.addSuppressed( saved );
         }
      }
   }
}

      

As rgettman stated, the JLS says that exceptions thrown from a finally clause usually cause other exceptions to be forgotten. Moral: Try not to throw exceptions from the finally clause.

0


source







All Articles