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
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}