ProgrammingHardWipro · Cognizant pattern
Does this compile?
Does this compile?
public class Main {
public static void main(String[] a) {
try {
throw new RuntimeException();
} catch (Exception e) {
System.out.print("generic");
} catch (RuntimeException e) {
System.out.print("specific");
}
}
}- A. Compiles and prints generic
- B. Compiles and prints specific
- C. No: catch (RuntimeException e) is unreachable because the preceding catch (Exception e) already covers it
- D. No: you cannot catch RuntimeException separately from Exception
Correct answer: C. No: catch (RuntimeException e) is unreachable because the preceding catch (Exception e) already covers it
Java requires catch clauses to be ordered from most specific to most general. Since RuntimeException is a subtype of Exception, placing catch (Exception e) first makes the later, more specific catch (RuntimeException e) unreachable code, which is a compile-time error.
More OOP with C++ and Java questions
- What is printed? java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) {…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; String c = new…
- What is printed? java public class Main { public static void main(String[] args) { String a = "hello"; String c = new…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { List<Integer> nums =…
- What is printed? java public class Main { static void risky(int x) throws Exception { if (x < 0) throw new Exception("neg")…
- What is printed? java public class Main { static String f(int x) { try { if (x == 0) throw new ArithmeticException("div0"); return "ok" +…