E4 Handling Exceptions in Java
E4 Handling Exceptions 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.
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.
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");
}
}
-----------------------------------------------------------------------------------