Java Exception Hierarchy: Throwable, Error, Exception - Quiz
Total: 5 questions
1. What is the exception hierarchy in Java and what branches does it have?
What is the exception hierarchy in Java and what branches does it have?
The Java exception hierarchy is a tree of classes rooted at java.lang.Throwable. Only objects of Throwable and its subclasses can be thrown with throw and caught in catch.
Throwable has two direct subclasses:
Error— serious JVM-level failures:OutOfMemoryError,StackOverflowError(both extendVirtualMachineError),NoClassDefFoundError. They are usually not handled.Exception— problems a program can handle:IOException,ParseException,SQLException,InterruptedException.
Inside Exception there is a separate RuntimeException branch for errors in program logic: NullPointerException, ArithmeticException, ClassCastException, IllegalArgumentException and its subclass NumberFormatException. The position of a class in the tree decides whether the exception is checked. Throwable itself is a class, not an interface: it extends Object and implements Serializable.
2. What is the difference between checked and unchecked exceptions in Java?
What is the difference between checked and unchecked exceptions in Java?
- Checked exceptions —
Exceptionand all its subclasses except theRuntimeExceptionbranch:IOException,FileNotFoundException,ParseException,SQLException. The compiler requires you to catch them or declare them inthrows, otherwise you getunreported exception ... must be caught or declared to be thrown. The cause is usually external: a file, the network, a database, the input format. - Unchecked exceptions —
RuntimeException,Errorand their subclasses:NullPointerException,NumberFormatException,OutOfMemoryError. The code compiles without handling them. The cause is a programmer error (fixed with checks in the code) or a JVM failure.
That is why Integer.parseInt("abc") compiles without try-catch (NumberFormatException extends RuntimeException), while NumberFormat.getInstance().parse("abc") does not (ParseException extends Exception directly). The Exception class itself is checked. The checked/unchecked split exists only for the compiler: at run time the JVM treats both kinds the same way.
3. How does Error differ from Exception, and why does catch (Exception e) not catch StackOverflowError?
How does Error differ from Exception, and why does catch (Exception e) not catch StackOverflowError?
Error describes JVM failures a program usually cannot fix: memory has run out (OutOfMemoryError), the call stack has overflowed (StackOverflowError). Exception describes predictable problems the code can handle: a file is not found, a string is not a number.
Error and Exception are sibling branches of the hierarchy; their only common ancestor is Throwable. So catch (Exception e) lets StackOverflowError and OutOfMemoryError pass: the error goes past it and terminates the program. It can be caught by catch (StackOverflowError e), catch (Error e) or catch (Throwable e).
Catching an Error is syntactically allowed, but recovering from it rarely works. Such a catch is used at most for logging and a clean shutdown, and catching Throwable “just in case” is a common mistake: it also silences JVM failures.
4. What are the most common exceptions in Java and what causes them?
What are the most common exceptions in Java and what causes them?
NullPointerException(unchecked) — calling a method or accessing a field throughnull. Since Java 15 the message is detailed:Cannot invoke "String.length()" because ... is null.ArrayIndexOutOfBoundsException(unchecked) — an array index below 0 or not less than the length:Index 4 out of bounds for length 3.ArithmeticException(unchecked) — integer division by zero:/ by zero.ClassCastException(unchecked) — casting an object to an incompatible type; the compiler lets it through, the error shows up only at run time.NumberFormatException(unchecked, a subclass ofIllegalArgumentException) —Integer.parseInt()got something that is not a number:For input string: "abc".IOException,FileNotFoundException(checked) — an input/output error, a file is not found.StackOverflowError,OutOfMemoryError(Error) — infinite recursion and running out of heap memory (Java heap space).
5. What are the main methods of the Throwable class?
What are the main methods of the Throwable class?
All exceptions and errors inherit the methods of Throwable; subclasses such as Exception add almost nothing to them:
getMessage()— the exception description ornull;getLocalizedMessage()returns the same by default.toString()— the class name and the message:java.lang.NumberFormatException: For input string: "abc". It is called when the exception is passed toprintln().getCause()— the cause exception ornull;initCause()sets the cause if it was not passed to the constructor (a second call throwsIllegalStateException).getStackTrace()— aStackTraceElement[]array; element[0]is the method where the exception was thrown.printStackTrace()— prints the stack trace toSystem.err(overloads exist forPrintStreamandPrintWriter).getSuppressed()— suppressed exceptions, for example those thrown while closing resources in try-with-resources (Java 7+).