Exception Handling in Java

Back to home
Logicmojo - Updated Jan 11, 2023



What is Exception Handling?

Exception handling does not imply exception repair. We must describe an alternate method of continuing the program; generally, this method of "creating an alternative" is nothing more than exception handling.

Example: If our programming requirement is to read data from a London file at runtime, our programme should not be terminated abnormally if the London file is not available. To continue with the rest of the programme normally, we must provide a local file. Exception handling is what this method of defining alternative is all about.


try
{
    read data from london file
}
catch(FileNotFoundException e)
{
    use local file and continue rest of the program normally
}


Runtime Stack Mechanism

JVM will construct a separate stack for each thread and keep all method calls made by that thread in that stack. "One activation record" (or "stack frame") refers to each entry in the stack. JVM removes the matching entry from the stack when each method call is completed. JVM eliminates the empty stack and ends the application properly after all method calls are completed.

class Main
{
    public static void main(String[] args){
        m1();
    }
    
    public static void m1(){
        m2();
    }
    
    public static void m2(){
        System.out.println("Hello");
    }
}


Default Exception Handling in Java

  1. 1. If an exception occurs inside a method, the method must construct an Exception object containing the following information.

    1. A. Name of the exception.

    2. B. Description of the exception.

    3. C. Location of the exception.

  2. 2. The method passes the Exception object to the JVM after it is created.

  3. 3. The JVM examines the method to see if it contains any exception handling code. If there is no handling code in a method, JVM terminates it abnormally and removes the associated element from the stack.

  4. 4. The JVM recognises the caller method and determines whether it contains any handling code. If the caller method does not have any handling code, JVM terminates it abnormally and removes the corresponding entry from the stack.

  5. 5. This process will continue until the main() function is reached, and if the main() method does not contain any exception handling code, JVM will stop it and remove the associated entry from the stack.

  6. 6. After that, the JVM delegated exception processing to the default exception handler.

  7. 7. The default exception handler just prints the following exception information to the console and stops the programme abnormally.

    1. Name of exception: description

    2. Location of exception (stack trace

Exception Hierarchy

Exceptions and errors of all kinds are subclasses of Throwable, which is the hierarchy's root class. One branch is under the control of Exception. This class is used when user programmes should be informed of uncommon events. The NullPointerException is an example of such an exception. Another branch, Error, is used by the Java run-time system (JVM) to discover faults with the run-time environment (JRE). An example of such an error is StackOverflowError.

Exception: Exceptions are caused by our programme in the vast majority of circumstances, and they are recoverable.

Error: The majority of errors are not produced by our application; rather, they are caused by a lack of system resources and are unrecoverable.

Types of Exception

In Java, there are two sorts of exceptions:

  1. 1. Checked exceptions

  2. 2. Unchecked exceptions

1. Checked exceptions

The exceptions which are checked by the compiler for smooth execution of the program at runtime are called checked exceptions.Checked exceptions are all exceptions other than Runtime Exceptions that the compiler checks during compilation to verify if the programmer has handled them or not. Compilation errors will occur if these exceptions are not handled/declared in the programme. SQLException, IOException, ClassNotFoundException, and so on.

2. Unchecked exceptions

Unchecked exceptions are exceptions that the compiler does not verify. Unchecked Exceptions are another name for Runtime Exceptions. The compiler has no way of knowing whether or not the programmer has dealt with these exceptions because they aren't examined during compilation. It is the job of the programmer to manage exceptions and ensure a safe exit. Examples of exceptions are ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, and more.

Customized exception handling by try catch

Risky code is code in our programme that may create an exception. We must insert risky code inside a try block and the related handling code inside a catch block.

Syntax

try
{
    risky code
}
catch(Exception e)
{
    handling code
}

Example

class Test
{
    public static void main(String[] args)
    {
        System.out.println("statement1");
        try
        {
            System.out.println(10/0);
        }
        catch(ArithmeticException e){
            System.out.println(10/2);
        }
        System.out.println("statement3");
    }
}

Try with multiple catch blocks

Because the way an exception is handled differs from one to the next, a new catch block is required for each exception. However, it is permissible and advised to use numerous catch blocks.

Example

class Test
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println(10/0);
        }
        catch(ArithmeticException e)
        {
            e.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Finally Block

🚀 It is never a good idea to put clean-up code within a try block since the execution of every statement inside a try is never guaranteed.

🚀 Clean up code should never be placed inside a catch block because if there is no exception, the catch block will not be executed.

🚀 We need a place to keep clean code that should be performed regardless of whether an exception is raised or not, and whether it is handled or not. This type of area is nothing more than a finally block.

🚀 Hence the main objective of finally block is to maintain cleanup code.

Syntax

try
{
    risky code
}
catch(x e)
{
    handling code
}
finally
{
    cleanup code
}

Example

class Test
{
    public static void main(String[] args)
    {
        try
        {
            System.out.println("try block executed");
            System.out.println(10/0);
        }
        catch(ArithmeticException e)
        {
            System.out.println("catch block executed");
        }
        finally
        {
            System.out.println("finally block executed");
        }
    }
}


With this article at Logicmojo, you must have the complete idea of Exception Handling in Java.