Enter your email id to get regular update free
Login
Your Email
Pasword

What is an Exception in Java and how to handle an exception?

Exception indicates the conditions that a reasonable application may try to catch.

What is an Exception in Java?
An exception is an  unexpected event which occurs during the execution of a program  at run time and it disrupts the normal flow of the program’s instructions.
An Error indicates serious problem that a reasonable application should not try to catch While an  Exception indicates conditions that a reasonable application might try to catch.  
Whenever inside a method  if an exception has occurred then the method creates an Object known as Exception Object.
Hierarchy of Exception
To handle Exception follow:
1.The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler.
2.The run-time system starts searching from the method in which exception occurred and proceeds through call stack in the reverse order in which methods were called.
3.If run-time system searches all the methods on call stack and couldn’t have find any appropriate handler then run-time system handover the Exception Object to default exception handler  This handler prints the exception information in the following format and terminates program abnormally.
Call stack flow.

To handle an Exception Need of try-catch clause:
// java program to demonstrateu need of try-catch clause
 class GFG {
 public static void main (String[] args)

 int[] arr = new int[4];
 // this statement causes an exception
 int i = arr[4];
 // the following statement will never execute
 System.out.println(" I want to execute");
 }
}

If you run above code on IDE then It will show the Output:
Exception in "main"java.lang.ArrayIndexOutOfBoundsException: 4 at GFG.main(GFG.java:9)
How to use try-catch clause?
try {
// block of code you think can raise an exception
 }
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
// optional finally
{
 // of code to be executed after try block ends
 }

In this method there can be more than one statements that may throw exception, So always put all these statements within its own try block and provide separate exception handler within own catch block for each of them.
Java
Exception
Exception handling
Ayesha
Tech writer at newsandstory
Total 102 views