ProgrammingVery hardProduct company OA
Does this compile (Java 7+)?
Does this compile (Java 7+)?
static void m() throws java.io.IOException, java.sql.SQLException {
try {
if (Math.random() < 2) throw new java.io.IOException();
else throw new java.sql.SQLException();
} catch (Exception e) {
throw e;
}
}- A. No: throw e; requires e's declared type Exception, so m() must declare throws Exception
- B. Yes, but only because Exception itself is unchecked
- C. No: you can never rethrow a caught Exception without a RuntimeException wrapper
- D. Yes: 'more precise rethrow' lets the compiler see e can only be IOException or SQLException, matching the throws clause
Correct answer: D. Yes: 'more precise rethrow' lets the compiler see e can only be IOException or SQLException, matching the throws clause
Since Java 7, if a caught multi-type variable like e is never reassigned, the compiler tracks the narrower set of types the try block could actually throw (IOException or SQLException) for rethrow analysis, so this compiles despite e's static type being Exception.
More OOP with C++ and Java questions
- Does this compile? java class A { void m() throws java.io.IOException {} } class B extends A { @Override void m() throws…
- What is printed, and what happens to the RuntimeException? java static int f() { try { throw new RuntimeException("x"); } finally { return…
- What is printed? java class MyEx extends RuntimeException { public String getMessage() { return "custom:" + super.getMessage(); } } public…
- Does this compile? java interface I { void m() throws java.io.IOException; } class C implements I { public void m() throws…
- 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 // in main: String a = "hello"; String b = "hello"; String c = new String("hello"); String d = c.intern()…