We can handle exceptions in Java using the try–catch mechanism. While running Java programs, we may encounter different kinds of exceptions. In Java, exceptions are mainly classified into checked and unchecked exceptions.
-
Checked exceptions are checked at compile time and must be handled using try–catch or declared using
throws. -
Unchecked exceptions occur at runtime and are not checked during compilation.
In the following example, the code throws an ArrayIndexOutOfBoundsException because we are trying to access index 3 of the nums array, which only has indices 0 to 2. We can handle this exception using a try–catch block as shown below.
Example Code:
try {
int[] nums = {1, 4, 5};
int val = nums[3];
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
Note:ArrayIndexOutOfBoundsException is an unchecked exception