[英]Why do I get compile error? using try and catch
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 0, y = 10;
try {
y /=x;
}
System.out.print(" / by 0");
catch(exception e) {
System.out.print("error");
}
}
使用 try and catch,我在上面构建了代码,output 是编译错误。 我预期的 output 是“错误”,因为数字除以零会产生 ArithmeticException。 为什么会出现上面的编译错误?
您不能将try
与catch
块分开。 这给了你编译错误。 正确的代码是:
public static void main(String[] args) {
int x = 0, y = 10;
try {
y /= x;
} catch (Exception e) {
System.out.print(" / by 0");
System.out.print("error");
}
}
此外,您有Exception
小写,这会导致另一个问题。
catch 块应该紧跟在 try 块之后。 将打印行语句放在 catch 块中。 此外,异常是 Java 的 class,不是异常。
因此,将 catch 关键字放在 try 块 (}) 结束后立即,或放在下一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.