java中异常处理和最终阻塞的怀疑
你能告诉我怎么做吗 代码:java中异常处理和最终阻塞的怀疑,java,exception-handling,Java,Exception Handling,你能告诉我怎么做吗 代码: public void main(String[] args) { try { //Some Exception throws here } catch(SomeException se) { se.printStackTrace(); } finally { try { //SomeException1 throws here }
public void main(String[] args) {
try {
//Some Exception throws here
}
catch(SomeException se) {
se.printStackTrace();
}
finally {
try {
//SomeException1 throws here
}
catch(SomeException1 se1) {
se.printStackTrace();
//Control is getting stop in this block itself but i wanna print the below statement
}
// I need to print this statement whatever exception occurs
System.out.println("End Program");
}
}
在主端点之前,在嵌套的try块中的第一个try块的外部打印如何
public void main(String[] args) {
try {
//Some Exception throws here
} catch(SomeException se) {
se.printStackTrace();
} finally {
try {
//SomeException1 throws here
} catch(SomeException1 se1) {
se.printStackTrace();
//Control is getting stop in this block itself but i wanna print the below statement
}
}
System.out.println("End Program"); // --- How about here? (Srikanth) ----
}
您正在捕获异常,因此您的程序不会突然结束。但是我猜它会被打印出来,不确定你在嵌套的catch块中到底在做什么。它是否抛出了一些运行时异常?看起来应该可以工作 有两个想法:
- 您可以将System.out.println(…)放在另一个finally块中
- 程序应该在catch块中停止的唯一方法是调用System.exit()。如果你叫出口,就这样。。。不再运行代码
- 堆栈跟踪将写入标准错误,但所需的行将写入标准输出。你是不是在把他们重定向到不同的地方
public void main(String[] args) {
try {
//Some Exception throws here
}
catch(SomeException se) {
se.printStackTrace();
}
finally {
try {
//SomeException1 throws here
}
catch(SomeException1 se1) {
se.printStackTrace();
}
finally {
System.out.println("End Program"); ----> I need to print this statement whatever exception occurs
}
}
}
或者,如果您知道只会有您处理的异常,您可以完全删除finally块。添加另一个finally块应该可以:
try {
//Some Exception throws here
} catch(SomeException se) {
se.printStackTrace();
} finally {
try {
//SomeException1 throws here
} catch(SomeException1 se1) {
se.printStackTrace();
} finally {
System.out.println("End Program");
}
}
另一种方式:
public void main(String[] args) {
boolean exceptionOccured = false;
try {
exceptionOccured = true;
//Some Exception throws here
exceptionOccured = false;
}
catch(SomeException se) {
se.printStackTrace();
}
finally {
Exception e = null;
try {
//SomeException1 throws here
}
catch(SomeException1 se1) {
exceptionOccured = true;
se.printStackTrace();
//Control is getting stop in this block itself but i wanna print the below statement
}
// I need to print this statement whatever exception occurs
if(exceptionOccured)
System.out.println("End Program");
}
}
我已经更新了我的答案,看看你的代码是否也是这样。还有,在嵌套的catch块(第二个块)中是否有运行时异常?在第二个块中,是否确实打印“se”而不是“se1”?我看不出你的程序在打印se1后停止的任何原因。你能给我们实际的代码吗?当你说“//控制在这个块本身停止”时,是不是你终止了程序本身的执行?(System.exit()或其他什么?)这没有意义,除非调用exit(),否则没有理由不调用“End Program”。您确定没有抛出除SomeException1之外的其他内容,这些内容不会被捕获,因此不会执行块的其余部分。这意味着控件不会在您认为的位置停止。这是唯一有意义的事情,如果额外的最终是使其工作。因此,finally中的catch(异常e)也可以工作。对于给定的代码,第二个finally块应该是不必要的。(实际上,第一个finally块也是如此。)@mmyers-是的,它表示问题不正确,并且finally中发生了另一个未捕获的异常。