Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
public class Main {
public static void main(String[] args) {
int d = 0;
try {
System.out.println(10 / d);
} catch (Exception e) {
System.out.println("error");
} catch (ArithmeticException e) {
System.out.println("zero");
}
}
}It does not compile
- Expecting
error: Java does take the first matchingcatchat run time, but here the compiler sees that the second one can never run and refuses the program. - Expecting
zero: Java does not pick the most specificcatch; it checks them top to bottom, so a subclass must come before its parent.
- How do you fix the program so that it prints
zero? - What does
catch (ArithmeticException | NumberFormatException e)do?