Java-Common Exception and Multiple Catch Blocks

Common Exception

Exception Type Cause of Exception
ArithmeticException Math errors such as divison by zero
ArrayIndexOutOfBoundsException Bad array indexes
ArrayStoreException When a program tries to store the wrong type of data in an array
FileNotFoundException An attempt to access a nonexistent file
IOException General input, output failures
NullPointerException Referencing a null object
NumberFormatException A conversion between strings and number fails

Multiple Catch Statement

In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed.



Program Source

class Javaapp {

    public static void main(String[] args) {
        String newArraySize = "Ten";
        int data[]={0};
        int dataposion = 11;
        int value = 0;
        int error = 0;
                data = new int[Integer.parseInt(newArraySize)];
                data[dataposion] = 200/value;
            }catch(NumberFormatException ne)
                System.out.println("Error "+error+" : Invalid parsing");
                newArraySize = "10";
            }catch(ArithmeticException ae)
                System.out.println("Error "+error+" : Division by zero");
                value = 2;
            }catch(ArrayIndexOutOfBoundsException ae)
                System.out.println("Error "+error+" : Array index invalid");
                dataposion = 1;
        System.out.println("All Runtime Errors Cleared");
        System.out.println("Data size is     : "+data.length);
        System.out.println("Data[1] value is : "+data[1]);

Leave a Comment