Rethrowing exceptions in Java without losing the stack trace

后端 未结 9 2081
挽巷
挽巷 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 19:44

    I would prefer:

    try
    {
        ...
    }
    catch (FooException fe){
       throw fe;
    }
    catch (Exception e)
    {
        // Note: don't catch all exceptions like this unless you know what you
        // are doing.
        ...
    }
    
    0 讨论(0)
  • 2020-11-28 19:49

    something like this

    try 
    {
      ...
    }
    catch (FooException e) 
    {
      throw e;
    }
    catch (Exception e)
    {
      ...
    }
    
    0 讨论(0)
  • 2020-11-28 19:54
    public int read(byte[] a) throws IOException {
        try {
            return in.read(a);
        } catch (final Throwable t) {
            /* can do something here, like  in=null;  */
            throw t;
        }
    }
    

    This is a concrete example where the method throws an IOException. The final means t can only hold an exception thrown from the try block. Additional reading material can be found here and here.

    0 讨论(0)
  • 2020-11-28 19:58

    You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:

    try
    {
       ...
    }
    catch (Exception e)
    {
         throw new YourOwnException(e);
    }
    
    0 讨论(0)
  • 2020-11-28 19:59

    Stack trace is prserved if you wrap the catched excetion into an other exception (to provide more info) or if you just rethrow the catched excetion.

    try{ ... }catch (FooException e){ throw new BarException("Some usefull info", e); }

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

    In Java is almost the same:

    try
    {
       ...
    }
    catch (Exception e)
    {
       if (e instanceof FooException)
         throw e;
    }
    
    0 讨论(0)
提交回复
热议问题