Java 即使在catch块中捕获了异常对象,我们也能将其抛出调用方法吗?
考虑一个示例代码:Java 即使在catch块中捕获了异常对象,我们也能将其抛出调用方法吗?,java,exception,exception-handling,Java,Exception,Exception Handling,考虑一个示例代码: public void someMethod() throws Exception{ try{ int x = 5/0; //say, or we can have any exception here } catch(Exception e){ if(counter >5){ // or any condition that depends on runtime inputs //something
public void someMethod() throws Exception{
try{
int x = 5/0; //say, or we can have any exception here
}
catch(Exception e){
if(counter >5){ // or any condition that depends on runtime inputs
//something here to throw to the calling method, to manage the Exception
}
else
System.out.println("Exception Handled here only");
}
}
这样的事情可能吗?如果是的话,那么如何用什么来代替“在这里抛出一些东西给调用方法,来管理异常”
也就是说,我的问题是,我们是否可以有条件地这样管理,我们是否希望在此处理异常。当然,您可以重新显示捕获的异常:
catch (Exception e) {
if (counter > 5) {
throw e; // Rethrow the exception
}
else {
System.out.println("Exception Handled here only");
// Or something more meaningful, for that matter
}
}
当然,您可以重新显示捕获的异常:
catch (Exception e) {
if (counter > 5) {
throw e; // Rethrow the exception
}
else {
System.out.println("Exception Handled here only");
// Or something more meaningful, for that matter
}
}
当然,你可以把你的接球挡投进去,没问题。您甚至可以在自己的有用异常中分层,并使用
Throwable(String message, Throwable cause)
构造器。例如,假设您有一个特殊的RetryLimitReachedException
,您可以像这样将其丢弃
catch (Exception e) {
if (counter > 5) {
throw new RetryLimitReachedException("Failed to do X, retried 5 times", e);
}
....
}
在stacktrace中,您将能够清楚地看到该类无法处理它,因此将其传递回。您将能够在由以下原因引起的
中看到导致不可处理异常情况的确切原因:代码>stacktrace的行。当然,您可以放入您的捕捉块,没有问题。您甚至可以在自己的有用异常中分层,并使用
Throwable(String message, Throwable cause)
构造器。例如,假设您有一个特殊的RetryLimitReachedException
,您可以像这样将其丢弃
catch (Exception e) {
if (counter > 5) {
throw new RetryLimitReachedException("Failed to do X, retried 5 times", e);
}
....
}
在stacktrace中,您将能够清楚地看到该类无法处理它,因此将其传递回。您将能够在由以下原因引起的中看到导致不可处理异常情况的确切原因:代码>stacktrace的行。除了抛出它,也许也不仅仅是抛出它