Interview Q&A · Java · 8 questions in this topic

Exceptions, Errors and Handling Strategies — Java Interview Q&A

All Java topics

What exceptions and errors are, why handling matters, and the basic strategies Java provides for dealing with failure. Part of Exception Handling · 294 questions in the Java bank.

What is an exception in Java?

Answer

An exception is an object that represents an abnormal event which disrupts the normal flow of a program. It is created either by the JVM when a runtime problem occurs or explicitly by application code. Every exception is an instance of a class rooted at java.lang.Throwable, with most application failures modeled as subclasses of java.lang.Exception.

Key points

  1. 1An exception carries a type, a message, and a stack trace describing where it occurred.
  2. 2It can be raised by the JVM, by library code, or by explicit throw statements.
  3. 3All standard exception classes live in java.lang, so no import is needed.

Example

Example.javajava
int[] a = new int[3];
int x = a[5]; // throws ArrayIndexOutOfBoundsException at runtime

In what situations do exceptions arise?

Answer

Common triggers include accessing an array with an invalid index, parsing a malformed number which throws NumberFormatException, casting an object to an incompatible type which throws ClassCastException, and dereferencing a null reference. Illegal method arguments and IO failures such as a missing file or a broken connection are other frequent causes. Trying to instantiate an interface or abstract class with new is a compile error rather than a runtime exception, although reflective creation can throw InstantiationException.

Key points

  1. 1ArrayIndexOutOfBoundsException from a bad array index.
  2. 2NumberFormatException from parsing invalid text such as Integer.parseInt("abc").
  3. 3ClassCastException from an illegal cast and NullPointerException from a null dereference.
  4. 4IllegalArgumentException from bad parameters and IOException from IO failures.

What is exception handling?

Answer

Exception handling is the mechanism Java provides for responding to runtime problems without letting the program terminate abruptly. Code that might fail is guarded so that when an exception occurs, control transfers to a handler that can log the problem, clean up, recover, or report a clear error. This separation keeps the normal success path readable and isolates recovery logic in dedicated blocks.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits