Handling Exceptions in Java
The following five keywords are used to handle an exception in Java:
1. try
2. catch
3. finally
4. throw
5. throws
try-catch:
It is highly recommended to handle exceptions. In our program the code which may raise
an exception is called risky code, we must place risky code inside the try block and the
corresponding handling code inside the catch block.
Control flow in try catch finally:
Abnormal Vs Normal Termination
If exception raised and corresponding catch block matched.
Default Exception Handling in Java: Default exception handler just print exception information to
the console and terminates the program abnormally.
If exception raised and corresponding catch block matched.
Without try catch With try catch
public class Test public class Test
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
int[] arr = {10, 20, 30}; int[] arr = {10, 20, 30};
System.out.println(arr[5]); try
// Invalid index {
} System.out.println(arr[5]);
} }
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println( arr[2]);
}
}
}
If exception raised and corresponding catch block not matched.
class Test
{
public static void main(String[] args)
{
try
{
System.out.println("try block executed");
System.out.println(10 / 0); // ArithmeticException occurs here
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("catch block executed");
}
finally
{
System.out.println("finally block executed");
}
}
}
Output : try block executed, finally block executed, Exception in thread "main"
java.lang.ArithmeticException: / by zero
Finally block: “I am always here”
It is used to perform clean-up activity such as closing resources, close database connection
regardless of whether an exception is thrown or not. The finally block always executes when
the try block exits.
class Sum
{
public static void main(String a[])
{
System.out.println("A");
System.out.println("B");
try
{
System.out.println(4/0);
}
catch(ArithmeticException e)
{
System.out.println(4/2);
}
finally
{
System.out.println("I am always Here");
}
System.out.println("C");
System.out.println("D");
}
}
-----------------------------------------------------------------------------------