1// A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following
2
3try {
4 // Protected code
5} catch (ExceptionName e1) {
6 // Catch block
7}
8The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.
9
10A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
11
12Example
13The following is an array declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception.
14
15// File Name : ExcepTest.java
16import java.io.*;
17
18public class ExcepTest {
19
20 public static void main(String args[]) {
21 try {
22 int a[] = new int[2]; // Size 2
23 System.out.println("Access element three :" + a[3]); // Accessing 3rd element
24 } catch (ArrayIndexOutOfBoundsException e) {
25 System.out.println("Exception thrown :" + e);
26 }
27 System.out.println("Out of the block");
28 }
29}
30