Exception Handling
- Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program
- When an exception occurs within a method, it creates an object - exception object. It contains information about the exception, such as the name and description of the exception and the state of the program when the exception occurred
- Error v/s Exception
- Error: An Error indicates a serious problem that a reasonable application should not try to catch
- Exception: Exception indicates conditions that a reasonable application might try to catch

- Types of exceptions
- Checked Exceptions:
- IOException: An exception is thrown when an input/output operation fails, such as when reading from or writing to a file
- SQLException: It is thrown when an error occurs while accessing a database
- ParseException: Indicates a problem while parsing a string into another data type, such as parsing a date
- ClassNotFoundException: It is thrown when an application tries to load a class through its string name using methods like Class.forName(), but the class with the specified name cannot be found in the classpath
- Unchecked Exceptions (Runtime Exceptions):
- NullPointerException: It is thrown when trying to access or call a method on an object reference that is null
- ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an invalid index
- ArithmeticException: It is thrown when an arithmetic operation fails, such as division by zero
- IllegalArgumentException: It indicates that a method has been passed an illegal or inappropriate argument
- Errors:
- OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate enough memory for the application
- StackOverflowError: It is thrown when the stack memory is exhausted due to excessive recursion
- NoClassDefFoundError: It indicates that the JVM cannot find the definition of a class that was available at compile-time
| Feature | Checked Exceptions | Unchecked Exceptions |
|---|---|---|
| Definition | Exceptions that are checked at compile-time | Exceptions that occur at runtime |
| Examples | IOException, SQLException, etc. | NullPointerException, ArithmeticException, etc. |
| Handling Requirement | Must be handled using try-catch or declared using throws | Not mandatory to handle or declare explicitly |
| Compile-Time Check | Checked by the compiler | Not checked by the compiler |
| Inheritance | Subclasses of Exception (excluding RuntimeException) | Subclasses of RuntimeException |
| Use Case | Used for predictable but unavoidable conditions (e.g., file not found) | Used for programming errors (e.g., divide by zero, null references) |
| Impact on Code | Forces the programmer to address the exception | Provides flexibility to handle errors only when necessary |
JVM Exception Handling Mechanism
-
Initial Exception Creation: When an exception occurs within a method, the JVM creates an Exception Object containing three key pieces of information:
- The exception’s name and description
- The current state of the program
- The point where the exception occurred
-
Call Stack Formation: The JVM maintains a Call Stack, which is an ordered list of all methods that were called leading up to the exception. This stack trace helps in tracking the exception’s origin and propagation path
-
Search for Exception Handler: The runtime system begins a systematic search through the call stack to locate an appropriate exception handler. This search process has specific characteristics:
- Starts from the method where the exception occurred
- Moves backwards through the call stack
- Looks for handlers that match the specific exception type
-
Handler Matching Process: When searching for an appropriate handler, the JVM checks for compatibility between the thrown exception type and the handler’s capability. A match occurs when the handler can process the specific type of exception object that was thrown
-
Default Exception Handling: If no appropriate handler is found after searching the entire call stack, the JVM activates its default exception handler, which:
- Prints the exception information in a standardized format
- Displays the complete stack trace
- Terminates the program abnormally
-
Program Termination: The final step in unhandled exceptions involves the JVM performing an abnormal program termination, ensuring that all resources are properly released and the program state is logged for debugging purposes
-
Let us see the below picutre to understand the flow of the call stack:

-
See this example (
ExceptionJvm.java, below) for better understandingExceptionJvm.java// This code demonstrates how Java's JVM handles exception propagation through the call stack. public class ExceptionJvm { public static void main(String[] args) { try { method1(); } catch (ArithmeticException e) { System.out.println("Exception caught in main: " + e.getMessage()); e.printStackTrace(); } } public static void method1() { method2(); } public static void method2() { method3(); } public static void method3() { // This will cause an ArithmeticException int result = 100 / 0; System.out.println(result); } }In the browser, messages of exceptions the JVM throws (like "/ by zero") come out as null. Run it on your computer with
java ExceptionJvm.java.Java 21
Java Exception Keywords
-
See this example (
AgeValidator.java, below) for better understandingAgeValidator.java// usage of keywords: 'throws', 'throw', 'try', 'catch', 'finally' class CustomException extends Exception { public CustomException(String message) { super(message); } } public class AgeValidator { // Method that declares it may throw an exception using 'throws' public static void validateAge(int age) throws CustomException { if (age < 0) { throw new CustomException("Age cannot be negative"); } System.out.println("Age is valid: " + age); } public static void main(String[] args) { try { // This will throw an exception validateAge(-5); } catch (CustomException e) { System.out.println("Caught exception: " + e.getMessage()); } finally { System.out.println("Finally block always executes"); } System.out.println("Program continues..."); } }Runs in your browser with Java 21. Ctrl/⌘ + Enter to run.Built with CheerpJ
| Keyword | Description |
|---|---|
| try | The “try” keyword is used to specify a block where we should place an exception code. It means we can’t use the try block alone. The try block must be followed by either catch or finally |
| catch | The “catch” block is used to handle the exception. It must be preceded by a try block, which means we can’t use the catch block alone. It can be followed by a finally block later |
| finally | The finally block is used to execute the necessary code of the program. It is executed whether an exception is handled or not |
| throw | The throw keyword is used to throw an exception. Propagate unchecked exception |
| throws | The throws keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn’t throw an exception. It is always used with a method signature. Propagate checked exception |