Skip to Content
bytegarden

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

  • Types of exceptions
  1. Checked Exceptions:
    1. IOException: An exception is thrown when an input/output operation fails, such as when reading from or writing to a file
    2. SQLException: It is thrown when an error occurs while accessing a database
    3. ParseException: Indicates a problem while parsing a string into another data type, such as parsing a date
    4. 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
  2. Unchecked Exceptions (Runtime Exceptions):
    1. NullPointerException: It is thrown when trying to access or call a method on an object reference that is null
    2. ArrayIndexOutOfBoundsException: It occurs when we try to access an array element with an invalid index
    3. ArithmeticException: It is thrown when an arithmetic operation fails, such as division by zero
    4. IllegalArgumentException: It indicates that a method has been passed an illegal or inappropriate argument
  3. Errors:
    1. OutOfMemoryError: It occurs when the Java Virtual Machine (JVM) cannot allocate enough memory for the application
    2. StackOverflowError: It is thrown when the stack memory is exhausted due to excessive recursion
    3. NoClassDefFoundError: It indicates that the JVM cannot find the definition of a class that was available at compile-time
FeatureChecked ExceptionsUnchecked Exceptions
DefinitionExceptions that are checked at compile-timeExceptions that occur at runtime
ExamplesIOException, SQLException, etc.NullPointerException, ArithmeticException, etc.
Handling RequirementMust be handled using try-catch or declared using throwsNot mandatory to handle or declare explicitly
Compile-Time CheckChecked by the compilerNot checked by the compiler
InheritanceSubclasses of Exception (excluding RuntimeException)Subclasses of RuntimeException
Use CaseUsed for predictable but unavoidable conditions (e.g., file not found)Used for programming errors (e.g., divide by zero, null references)
Impact on CodeForces the programmer to address the exceptionProvides 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:
    call stack

  • See this example (ExceptionJvm.java, below) for better understanding

    ExceptionJvm.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 understanding

    AgeValidator.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
KeywordDescription
tryThe “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
catchThe “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
finallyThe finally block is used to execute the necessary code of the program. It is executed whether an exception is handled or not
throwThe throw keyword is used to throw an exception. Propagate unchecked exception
throwsThe 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