Write a Program to show try catch example?

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Approach

Java


public class TryCatch1 {
    public static void main(String[] args) {
        try {
            List<Integerl = null;
            System.out.println(l.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Approach: Multi  catch block

Java


import java.util.ArrayList;
import java.util.List;

public class TryCatch1 {
    public static void main(String[] args) {
        try {
            List<Integerl = new ArrayList<Integer>();
            System.out.println(l.get(2));
        } catch (IndexOutOfBoundsException e) {
            System.out.println("IndexOutOfBoundsException");
        } catch (Exception e) {
            System.out.println("Other Exception");
        }
    }
}

Approach: Multiple exception handling

Java



import java.util.ArrayList;
import java.util.List;

public class TryCatch1 {
    public static void main(String[] args) {
        try {
            List<Integerl = new ArrayList<Integer>();
            System.out.println(l.get(2));
        } catch (IndexOutOfBoundsException | NullPointerException e) {
            System.out.println("IndexOutOfBoundsException | NullPointerException");
        }
    }
}

}



No comments:

Post a Comment