ProgrammingModerateProduct-company placement · Java

What is printed?

What is printed?
class AppEx extends Exception { }
class DbEx extends AppEx { }
// static method of the main class:
static void run() throws AppEx { throw new DbEx(); }
// in main:
try { run(); }
catch (DbEx e)  { System.out.print("Db"); }
catch (AppEx e) { System.out.print("App"); }
  1. A. Db
  2. B. App
  3. C. DbApp
  4. D. Compile-time error: run() does not declare DbEx

Correct answer: A. Db

The throws clause names a supertype, but handlers are matched against the actual runtime class, a DbEx, so the first (more specific) handler runs.

More OOP with C++ and Java questions

Exams that ask this topic