在Java中捕获和声明异常?

huangapple go评论56阅读模式
英文:

Caught and declared exception in Java?

问题

在Java中,如果我声明并捕获了一个异常,我能在调用者中无论如何处理这个异常吗?还是说调用者在处理它时不需要捕获它?

class A {
  void first() throws Exception { 
    try {
      throw new Exception("my exception");
    } catch (Exception e) {
      log.message("Error in first()", e.getCause());
      throw e;
    }
  }
}

class B {
  Result second(A a) {
    try {
      a.first();
    } catch (Exception e) {
      log.message("Caught in B class", e.getMessage());
      return new Result(result: null, error: e.getMessage());
    }
  }

  second(A a);
}
英文:

In Java, if I declare and caught an exception, can I handle the exception in a caller anyway? Or it needs not to be caught to handle it by caller?

class A {
  void first() throws Exception { 
    try {
      throw new Exception("my exception")
    } catch (Exception e) {
      log.message("Error in first()", e.getCouse)
      throw e
    }
  }
}

class B {
  Result second(A a) {
    try {
      a.first()
    } catch (Exception e) {
      log.message("Caught in B class", e.message)
      return new Result(result: null, error: e.message)
    }
  }

  second(A a)
}

答案1

得分: 3

你可以简单地重新抛出你捕获的异常(显然,周围的方法必须通过其签名等允许这样做)。异常将保留原始的堆栈跟踪。

catch (WhateverException e) {
    throw e;
}

你也可以将异常包装在另一个异常中,并通过将 Exception 作为原因参数传递来保留原始的堆栈跟踪:

try
{
   ...
}
catch (Exception e)
{
     throw new YourOwnException(e);
}
英文:

You can 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.

catch (WhateverException e) {
    throw e;
}

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);
}

huangapple
  • 本文由 发表于 2020年10月7日 15:05:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64238904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定