首页 文章

在不丢失堆栈跟踪的情况下重新使用Java中的异常

提问于
浏览
360

在C#中,我可以使用 throw; 语句在保留堆栈跟踪的同时重新抛出异常:

try
{
   ...
}
catch (Exception e)
{
   if (e is FooException)
     throw;
}

在Java( that doesn't lose the original stack trace )中有这样的东西吗?

8 回答

  • 5

    这样的事情

    try 
    {
      ...
    }
    catch (FooException e) 
    {
      throw e;
    }
    catch (Exception e)
    {
      ...
    }
    
  • 489
    catch (WhateverException e) {
        throw e;
    }
    

    将简单地重新抛出你捕获的异常(显然,周围的方法必须通过其签名等来允许) . 该异常将保持原始堆栈跟踪 .

  • 79

    我会比较喜欢:

    try
    {
       ...
    }
    catch (FooException fe){
       throw fe;
    }
    catch (Exception e)
    {
       ...
    }
    
  • 0

    您还可以将异常包装在另一个异常中并通过将Exception作为Throwable作为cause参数传递来保留原始堆栈跟踪:

    try
    {
       ...
    }
    catch (Exception e)
    {
         throw new YourOwnException(e);
    }
    
  • 5

    在Java中几乎是一样的:

    try
    {
       ...
    }
    catch (Exception e)
    {
       if (e instanceof FooException)
         throw e;
    }
    
  • 21

    在Java中,你只是抛出你捕获的异常,所以 throw e 而不仅仅是 throw . Java维护堆栈跟踪 .

  • 66
    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;
        }
    }
    

    这是方法抛出 IOException 的具体示例 . final 表示 t 只能保存try块抛出的异常 . 其他阅读材料可以在herehere找到 .

  • 13

    如果将捕获的异常包装到另一个异常(提供更多信息)或者只是重新抛出捕获的异常,则堆栈跟踪会被破坏 .

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

相关问题