Rethrowing exceptions in Java without losing the stack trace

后端 未结 9 2082
挽巷
挽巷 2020-11-28 19:18

In C#, I can use the throw; statement to rethrow an exception while preserving the stack trace:

try
{
   ...
}
catch (Exception e)
{
   if (e is         


        
相关标签:
9条回答
  • 2020-11-28 20:02

    In Java, you just throw the exception you caught, so throw e rather than just throw. Java maintains the stack trace.

    0 讨论(0)
  • 2020-11-28 20:04
    catch (WhateverException e) {
        throw e;
    }
    

    will simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.

    0 讨论(0)
  • 2020-11-28 20:05

    I was just having a similar situation in which my code potentially throws a number of different exceptions that I just wanted to rethrow. The solution described above was not working for me, because Eclipse told me that throw e; leads to an unhandeled exception, so I just did this:

    try
    {
    ...
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException e) {                    
        throw new RuntimeException(e.getClass().getName() + ": " + e.getMessage() + "\n" + e.getStackTrace().toString());
    }
    

    Worked for me....:)

    0 讨论(0)
提交回复
热议问题