Java Class

An easy to follow example in how to handle errors with exceptions in Java. In the example that I provide you will be able to see three exceptions, the first one handles a numerator which divides itself by 0 – something that is not possible – so the catch will show you what the problem is. The same goes for the NullPointerException one and the ArrayIndexOutOfBoundsException one.

public class ExceptionPractice {
    
    public static void main(String[] args){
        
        /*
        try {
            
            int numerator = 10, denominator = 0;
            System.out.println("Level 3 beginning.");
            int result = numerator / denominator;
            System.out.println("Level 3 ending.");
            
        } catch (ArithmeticException problem) {
            
            System.out.println();
            System.out.println("The exception message is: " +
                    problem.getMessage());
            System.out.println();
            System.out.println("The call stack trace:");
            problem.printStackTrace();
            System.out.println();
            
        }
        */
        /*
        try{
            String zero = null;
            // Print it
            zero.toString(); // Since zero is null, it is not possible to convert it into string so it will throw an NullPointerException
        } catch(NullPointerException problem2){
            System.out.println();
            System.out.println("The exception message is: " +
                    problem2.getMessage());
            System.out.println();
            System.out.println("The call stack trace:");
            problem2.printStackTrace();
            System.out.println();
        }
        */
        
        try{
            int[] arrayContainer = new int[5]; // Declare the container to only have 5 elements starting from 0;
            arrayContainer[0] = 0;
            arrayContainer[1] = 1;
            arrayContainer[2] = 2;
            arrayContainer[3] = 3;
            arrayContainer[4] = 4;
            arrayContainer[5] = 5; // Since 5 ends up being the number 6 element which can not be accessed, it creates an ArrayIndexOutOfBoundsException
        } catch(ArrayIndexOutOfBoundsException problem3){
            System.out.println();
            System.out.println("The exception message is: " +
                    problem3.getMessage());
            System.out.println();
            System.out.println("The call stack trace:");
            problem3.printStackTrace();
            System.out.println();
        }
        
    }
}

Bye-Bye 🙂

Leave a Reply

Back to Top