1try block: code that is protected for any exceptions. and it is mandatory (only try)
2catch block: if any exception happens during runtime in the try block,
3the catch block will catch that exception.
4if any exception happens during runtime in the try block,
5control will be given to catch block.
6An optional finally block gives us a chance to run the code which
7we want to execute EVERYTIME a try-catch block is completed
8– either with errors or without any error.
1class JavaException {
2 public static void main(String args[]) {
3 int d = 0;
4 int n = 20;
5 try {
6 int fraction = n / d;
7 System.out.println("This line will not be Executed");
8 } catch (ArithmeticException e) {
9 System.out.println("In the catch Block due to Exception = " + e);
10 }
11 System.out.println("End Of Main");
12 }
13}
1//The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
2
3Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
4
5A finally block appears at the end of the catch blocks and has the following syntax
6
7try {
8 // Protected code
9} catch (ExceptionType1 e1) {
10 // Catch block
11} catch (ExceptionType2 e2) {
12 // Catch block
13} catch (ExceptionType3 e3) {
14 // Catch block
15}finally {
16 // The finally block always executes.
17}
18Example
19public class ExcepTest {
20
21 public static void main(String args[]) {
22 int a[] = new int[2]; // Size 2
23 try {
24 System.out.println("Access element three :" + a[3]); // Accessing 3rd element
25 } catch (ArrayIndexOutOfBoundsException e) {
26 System.out.println("Exception thrown :" + e);
27 }finally { // Always executed no matter what!
28 a[0] = 6;
29 System.out.println("First element value: " + a[0]);
30 System.out.println("The finally statement is executed");
31 }
32 }
33}
34Output :
35Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
36First element value: 6
37The finally statement is executed