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 {
2 // Block of code to try
3}
4catch(Exception e) {
5 // Block of code to handle errors
6}
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.