1try {
2 // Code that may have error
3} catch(ErrorName e){
4 // Another code
5}
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 // Code to try, which is throwing an Exception, e.g.
3 /*example*/ Thread.sleep(100)
4} catch (InterruptedException e /*Or any other exception*/) {
5 // Handle Exception, usually:
6 e.printStackTrace(); // Print the StackTrace of the exception to see what cause it
7} finally {
8 // Code executed after try / catch, used to close streams
9 /*example*/ in.close();
10}
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.