Exceptions in Java


What is an Exception?

An exception is an event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

When an error occurs in a method, the method creates an Object known as Exception Object and hands it off to the runTime system. The exception object contains information about the error, type of the error, and current state of the program when an error has occured. Creating the Exception Object and handling it to the runTime system is called throwing an Exception.

Error vs Exception

Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

How to handle Exception?

There might be the list of the methods that had been called to get to the method where error occured. This ordered list of the methods is called Call Stack.

  • The runTime system searches the call stack to find the method that contains block of code that can handle the occured exception. The block of the code is called Exception handler.
  • The runTime system starts searching from the method in which exception occured, proceeds through call stack in the reverse order in which methods were called.
  • If it finds appropriate handler then it passes the occured exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
  • If runTime system searches all the methods on call stack and couldn’t have found the appropriate handler then the runTime system and consequently the running program terminates.

NOTE: All exception types are subclasses of class Throwable, which is at the top of exception class hierarchy.

Example :


// Java program to demonstrate how exception is thrown.
class ThrowsExecp{
    
	public static void main(String args[]){
	    
        String str = null;
        System.out.println(str.length());
		
	}
}


Output :

Exception in thread "main" java.lang.NullPointerException
	at ThrowsExecp.main(File.java:8)

An Example that illustrate how runTime system searches appropriate exception handler on the call stack :


// Java program to demonstrate exception is thrown
// how the runTime system searches th call stack
// to find appropriate exception handler.
class ExceptionThrown{
    
    // It throws the Exception.
    // Exception handler is not found within this method.
    static int divideByZero(int a, int b){
        
        if(b == 0){
            throw new ArithmeticException("Numerator should not be Zero.");
        }
        
        int i = a/b;
        return i;
    }
    
    // The runTime System searches the appropriate Exception handler
    // in this method also but couldn't have found. So looking forward
    // on the call stack.
    static int computeDivision(int a, int b) {
        
        int res =0;
        
        try
        {
          res = divideByZero(a,b);
        }
        catch(NumberFormatException ex)
        {
           System.out.println("NumberFormatException is occured."); 
        }
        return res;
    }
    
    // In this method found appropriate Exception handler.
    // i.e. matching catch block.
	public static void main(String args[]){
	    
        int a = 1;
        int b = 0;
        
        try
        {
            int i = computeDivision(a,b);
        
        }
        catch(ArithmeticException ex)
        {
            System.out.println(ex.getMessage());
        }
	}
}


Output :

Numerator should not be Zero.

See the below diagram to understand the flow of the call stack.

Related Articles:

Reference :
https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Source link

Leave a Reply