在异常行之后执行行时,任何人都可以帮助编写逻辑。在代码中我捕获了异常,但我想打印行“”在异常从同一个地方捕获后不会打印“”。
public static void main(String args[]) {
int d, a;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
答案 0 :(得分:2)
bool mExceptionOccur = false;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
mExceptionOccur = true;
System.out.println("Division by zero.");
}finally{
if (mExceptionOccur)
System.out.println("After catch statement. Exception Occurred");
else
System.out.println("After catch statement. No Exception Occurred");
}
使用try-catch-finally语句。无论是否捕获到异常,都将始终执行finally部分。
通过添加变量,您可以监视在执行finally部分之前是否抛出了异常。
答案 1 :(得分:-4)
怎么样:
public static void main(String args[]) {
int d, a;
try {
// monitor a block of code.
System.out.println("This will not be printed.");
d = 0;
a = 42 / d;
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}