Loading...

Exception Handling

Exception Handling is a mechanism to handle runtime errors, ensuring the normal flow of the application can be maintained.

Throwable

The superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the JVM.

Exception

An event that disrupts the normal flow of the program. It is mainly caused by the application itself and can be handled.

Error

Indicates a serious problem that a reasonable application should not try to catch (e.g., OutOfMemoryError). It is usually unrecoverable.

Checked Exceptions

Exceptions checked at Compile Time. The compiler forces you to handle them (try-catch) or declare them (throws).

Example: IOException, SQLException

Unchecked Exceptions

Exceptions checked at Run Time. The compiler does not check these. They usually result from programming logic errors.

Example: NullPointerException, ArrayIndexOutOfBoundsException

Java Exception Keywords

Keyword Description
try Specifies a block of code to test for errors. Must be followed by catch or finally.
catch Executes if an exception occurs in the try block. Handles the exception.
finally Executes code after try/catch, regardless of result. Used for cleanup (closing files, etc).
throw Used to explicitly throw an exception.
throws Used in method signatures to declare that a method might throw an exception.

Rules for Exception Handling with Method Overriding

Rule 1: Parent declares NO Exception
  • Child can declare Unchecked exceptions.
  • Child cannot declare Checked exceptions.
Rule 2: Parent declares Unchecked Exception
  • Child can declare any Unchecked exception.
  • Child cannot declare Checked exceptions.
Rule 3: Parent declares Checked Exception
  • Child can declare the same exception.
  • Child can declare a subclass of that exception.
  • Child can declare no exception.
Rule 4: Mixed Exceptions
  • Rules follow the hierarchy constraint: Child cannot throw a broader Checked exception than the Parent.

Difference Between Error and Exception

Error Exception
Impossible to recover (Unrecoverable). Can be recovered using try-catch.
Always Unchecked (java.lang.Error). Can be Checked or Unchecked.
Happens at Runtime. Happens at Compile-time or Runtime.
Caused by environment (JVM, Hardware). Caused by the application code/logic.
Common Checked Exceptions
ClassNotFoundException Class definition not found.
InterruptedException Thread interrupted while waiting.
IOException Failed I/O operation.
SQLException Database access error.
FileNotFoundException File does not exist.
Common Unchecked Exceptions
ArithmeticException Math error (e.g., divide by zero).
NullPointerException Accessing object that is null.
ArrayIndexOutOfBounds Invalid array index.
NumberFormatException Invalid string-to-number conversion.
ClassCastException Invalid type casting.