DEV Community

PRIYA K
PRIYA K

Posted on

Exception Handling in Java

An exception is an event, which occurs during the execution of a program,that disrupts the normal flow of the program's instructions.
An exception is an error that happens while the program is running.
Because of that error, the normal execution stops.

Example

public class Main {
    public static void main(String[] args) {

        int a = 10;
        int b = 0;

        System.out.println(a / b);

        System.out.println("Program Ends");
    }
}
Enter fullscreen mode Exit fullscreen mode

What happens?
a / b
means:
10 / 0
Division by zero is not allowed.
So Java throws:
Arithmetic Exception

Program stops before:

System.out.println("Program Ends");
Enter fullscreen mode Exit fullscreen mode

This is called:
disrupting the normal flow of the program.

When an error occurs within a method,the method creates an object and hands it off to the runtime system.

When error occurs:
Java creates an exception object
sends it to JVM/runtime system.

Example

public class Main {
    static void divide() {
        int x = 10 / 0;
    }
    public static void main(String[] args) {
        divide();
    }
}
Enter fullscreen mode Exit fullscreen mode

What happens?
Inside:
divide()
error occurs.

Java creates object:
Arithmetic Exception object and gives it to JVM.
The object, called an exception object,contains information about the error.

The exception object stores:
error type
error message
line number
method details

Example

Exception in thread "main"
java.lang.Arithmetic Exception: / by zero
Enter fullscreen mode Exit fullscreen mode

Information stored:
Information Value
Exception type Arithmetic Exception
Error message / by zero
Thread main

Including its type and state of the program.

Java remembers:
where error happened
what methods were running
current program state

Example

static void test() {
    int a = 10 / 0;
}

Enter fullscreen mode Exit fullscreen mode

Java remembers:

error inside test()
Enter fullscreen mode Exit fullscreen mode

line number
method calls

Creating an exception object is called throwing an exception
Creating an exception object and handing it to the runtime system is called throwing an exception.
Java sends the exception to JVM.

This process is called:
throwing an exception

Example
Automatic throwing:

int x = 10 / 0;
Enter fullscreen mode Exit fullscreen mode

Java automatically throws:
Arithmetic Exception
Manual throwing
throw new Arithmetic Exception();
Here programmer throws exception manually.

After a method throws an exception.
After a method throws an exception,
the runtime system attempts to find something to handle it.

JVM searches for:
catch
block to handle the exception.

Example

try {
    int x = 10 / 0;
}
catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
Enter fullscreen mode Exit fullscreen mode

Output:
Cannot divide by zero
Now program does not crash.

The set of possible somethings.
The set of possible "somethings" to handle the exception is the ordered list of methods that had been called

Java checks method calls one by one.
It searches where exception can be handled.

“The list of methods is known as call stack”
The order of method calls is called:
Call Stack

Example of Call Stack
class Main {

static void method1() {
    method2();
}

static void method2() {
    method3();
}

static void method3() {
    int x = 10 / 0;
}

public static void main(String[] args) {
    method1();
}
Enter fullscreen mode Exit fullscreen mode

}

Flow
main()

method1()

method2()

method3()

Exception occurs

This chain is called:
Call Stack
Stack Trace

Java prints:
Exception in thread "main"
java.lang.Arithmetic Exception: / by zero.

This shows:
where exception started
how methods were called

Simple Summary
Exception Runtime error
Exception Object Object containing error info
Throwing Exception Sending exception to JVM
Handling Exception Using try-catch
Call Stack Order of method calls
Stack Trace Printed error path

The runtime system searches the call stack for a method that contains a block of code that can handle the exception.
When an exception occurs:
JVM checks method calls one by one searches for a catch block
This searching happens in the call stack.

Example

class Main {

    static void method1() {
        method2();
    }

    static void method2() {
        int x = 10 / 0;
    }

    public static void main(String[] args) {
        method1();
    }
}
Enter fullscreen mode Exit fullscreen mode

What happens?
Call stack:
main()

method1()

method2()

Exception occurs inside:
method2()

JVM starts searching:
method2()
method1()
main()
for a catch block.

This block of code is called an exception handler.
The catch block is called:
Exception Handler
because it handles the exception.

Example

try {
    int x = 10 / 0;
}
catch (ArithmeticException e) {
    System.out.println("Error handled");
}
Enter fullscreen mode Exit fullscreen mode

Here:
catch (ArithmeticException e)
is the exception handler.

The search begins with the method in which the error occurred
JVM first checks the method where exception happened.

Example

static void method2() {

    try {
        int x = 10 / 0;
    }

    catch (ArithmeticException e) {
        System.out.println("Handled in method2");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Handled in method2
JVM found handler immediately in same method.

And proceeds through the call stack in reverse order proceeds through the call stack in the reverse order
If handler is not found:
JVM goes backward through method calls.

Example

class Main {

    static void method1() {
        method2();
    }

    static void method2() {
        int x = 10 / 0;
    }

    public static void main(String[] args) {

        try {
            method1();
        }

        catch (ArithmeticException e) {
            System.out.println("Handled in main");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Flow
main()

method1()

method2()

Exception in method2.
No catch there.
JVM moves backward:
method2 → method1 → main
Finally handler found in main().

Output:
Handled in main

When an appropriate handler is found,the runtime system passes the exception to the handler.
If matching catch block is found:
JVM sends exception object to catch block,catch block executes.

Example

try {
    int x = 10 / 0;
}

catch (Arithmetic Exception e) {
    System.out.println(e);
}
Enter fullscreen mode Exit fullscreen mode

Output:
java.lang.ArithmeticException: / by zero

The exception object is passed into:
e

An exception handler is considered appropriate, if the type of the exception object thrown matches the type that can be handled by the handler.
Catch type must match exception type.

Example

try {
    int x = 10 / 0;
}

catch (ArithmeticException e) {
    System.out.println("Handled");
}

Enter fullscreen mode Exit fullscreen mode

Exception type:
Arithmetic Exception
Catch type:
Arithmetic Exception
So handled successfully.

Example
try {
int x = 10 / 0;
}

catch (Null PointerException e) {
System.out.println("Handled");
}

Not handled.

Because:
Arithmetic Exception ≠ Null Pointer Exception

The exception handler chosen is said to catch the exception.
When catch block handles error:
Exception is caught

Example

catch (Arithmetic Exception e)
Enter fullscreen mode Exit fullscreen mode

This block catches the exception.

If the runtime system exhaustively searches all methods on the call stack without finding an appropriate exception handler

If JVM cannot find matching catch block anywhere:
exception remains unhandled

Example

class Main {

    public static void main(String[] args) {

        int x = 10 / 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

No try-catch.
JVM searches:
main()
No handler found.

the runtime system terminates
the runtime system (and consequently the program)
terminates
Program stops immediately.
Output

Exception in thread "main"
java.lang.ArithmeticException: / by zero
Enter fullscreen mode Exit fullscreen mode

Program crashes.

Exception occurs

JVM creates exception object

Searches current method

Searches call stack backward

Matching catch found
YES → Handle exception
NO → Program terminates

Example

class Main {
    static void test() {
        int x = 10 / 0;
    }

    public static void main(String[] args) {

        try {
            test();
        }

        catch (ArithmeticException e) {
            System.out.println("Exception handled");
        }

        System.out.println("Program continues");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
Exception handled
Program continues

Because JVM found appropriate handler in main().

Top comments (0)