你能说出怎么做的想法吗?
代码:
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");
}
}
答案 0 :(得分:7)
添加另一个finally块
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块。
答案 1 :(得分:2)
看起来它应该有效。
一些想法:
您可以将System.out.println(...)放在另一个finally块中。
程序在该catch块中停止的唯一方法是调用System.exit()。如果你调用exit,那就是它......不再运行代码。
堆栈跟踪被写入标准错误,但您想要的行被写入标准输出。你可以将它们重定向到不同的地方吗?
答案 2 :(得分:2)
添加另一个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");
}
}
答案 3 :(得分:1)
如何在主要结束之前在嵌套的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块中做了什么。是抛出一些RuntimeException吗?
答案 4 :(得分:0)
其他方式:
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");
}
}