[英]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");
}
}
Using try and catch, I have built code above and the output is compile error.使用 try and catch,我在上面构建了代码,output 是编译错误。 The output I expected was "error" since a number divided by zero gives an ArithmeticException.
我预期的 output 是“错误”,因为数字除以零会产生 ArithmeticException。 Why do I get compile error above?
为什么会出现上面的编译错误?
You can't seperate the try
from the catch
block.您不能将
try
与catch
块分开。 This got you the compilation error.这给了你编译错误。 Correct code would be:
正确的代码是:
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");
}
}
Also, you had Exception
lowercase, which would have caused another problem.此外,您有
Exception
小写,这会导致另一个问题。
A catch block is supposed to be immediately followed by try block. catch 块应该紧跟在 try 块之后。 Put the print line statement inside catch block.
将打印行语句放在 catch 块中。 Also, Exception is a class of Java, exception is not.
此外,异常是 Java 的 class,不是异常。
So, put the catch keyword immediately after the try block (}) ends, or in the next line.因此,将 catch 关键字放在 try 块 (}) 结束后立即,或放在下一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.