1public class MyClass {
2 public static void main(String[ ] args) {
3 try {
4 int[] myNumbers = {1, 2, 3, 4, 5, 6};
5 System.out.println(myNumbers[10]);
6 } catch (Exception e) {
7 System.out.println("Something went wrong. check again");
8 }
9 }
10}
11
1I use try & catch blocks to handle any exceptions in my code.
2 I am familiar with major checked and unchecked exceptions and
3 handle it accordingly to make my code execution smooth
1In java exception is an object. Exceptions are created when an abnormal
2situations are arised in our program. Exceptions can be created by JVM or
3by our application code. All Exception classes are defined in java.lang.
4In otherwords we can say Exception as run time error.
5
1An exception is an event, which occurs during the execution of a
2program, that disrupts the normal flow of the program's instructions.
1try block: code that is protected for any exceptions. and it is mandatory
2(only try)
3catch block: if any exception happens during runtime in the try block,
4the catch block will catch that exception.
5if any exception happens during runtime in the try block,
6control will be given to catch block.
7An optional finally block gives us a chance to run the code which
8we want to execute EVERYTIME a try-catch block is completed
9– either with errors or without any error.
1public class ExcepTest {
2
3 public static void main(String args[]) {
4 int a[] = new int[2];
5 try {
6 System.out.println("Access element three :" + a[3]);
7 } catch (ArrayIndexOutOfBoundsException e) {
8 System.out.println("Exception thrown :" + e);
9 }finally {
10 a[0] = 6;
11 System.out.println("First element value: " + a[0]);
12 System.out.println("The finally statement is executed");
13 }
14 }
15}