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. The output I expected was "error" since a number divided by zero gives an ArithmeticException. Why do I get compile error above?
You can't seperate the try
from the catch
block. 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.
A catch block is supposed to be immediately followed by try block. Put the print line statement inside catch block. Also, Exception is a class of Java, exception is not.
So, put the catch keyword immediately after the try block (}) ends, or in the next line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.