Exception Handling is a mechanism to handle runtime errors, ensuring the normal flow of the application can be maintained.
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.
An event that disrupts the normal flow of the program. It is mainly caused by the application itself and can be handled.
Indicates a serious problem that a reasonable application should not try to catch (e.g., OutOfMemoryError). It is usually unrecoverable.
Exceptions checked at Compile Time. The compiler forces you to handle them (try-catch) or declare them (throws).
Example: IOException, SQLExceptionExceptions checked at Run Time. The compiler does not check these. They usually result from programming logic errors.
Example: NullPointerException, ArrayIndexOutOfBoundsException| 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. |
| 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. |
| ClassNotFoundException | Class definition not found. |
| InterruptedException | Thread interrupted while waiting. |
| IOException | Failed I/O operation. |
| SQLException | Database access error. |
| FileNotFoundException | File does not exist. |
| 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. |