Exception handling in java

              Exceptions are errors that can appear in any program.it can be a compile or run time errors. Compile time errors can be corrected by the user itself many times. But runtime errors can be easily handled by exception handling mechanisms in java.

              Eg: IOException, SQLException, ClassNotFoundExceptions….

What is Exception?

              An exception is unexpected event or error which happens at run time. It affects the flow of program. Java Exceptions create an object. It has the information’s about the name of the exception and its information.

The reason behind the exception:

  • ·       Physical limitations
  • ·       Loss of network connection
  • ·       Device failure
  • ·       Invalid user input
  • ·       Arithmetic errors
  • ·       Array out of bound
  • ·       Type mismatch
  • ·       Null reference
  • ·       Database errors
  • ·       File errors

Some of the exceptions are given below.

    1.  Arithmetic expression :Divide by zero

    2.       Array out of boundry

    3.       NullpointerException

1.Arithmetic expression :Divide by zero:

              Creating two variables x,y. assign values for  x=15,y=0. Using a cry,catch block, divide this variables. Next, Print the exception.

 import java.io.*;

class arithException {

    public static void main (String[] args) {

      int x=15;

      int y=0;

        try{

          System.out.println(x/y);

        }

      catch(ArithmeticException e){

        System.out.println(e.toString());

      }

    }

}

Output:

C:\raji\blog>javac arithException.java

C:\raji\blog>java arithException

java.lang.ArithmeticException: / by zero

2.Array out of boundry :

              Create an array with 6 elements. Print the array of 7th element. It causes  ArrayIndexOutOfBoundsException.

class Exception1 {   

   public static void main(String args[]) 

   { 

    int num[] ={23,34,45,56,67,78}; 

    System.out.println(num[7]); 

   } 

} 

Output:

C:\raji\blog>javac Exception1.java

C:\raji\blog>java Exception1

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 6

        at Exception1.main(Exception1.java:5)

3. NullpointerException:

              Create a null array and print the length of the array. It causes the nullpointerException.

class Exception2 {

    // Main method

    public static void main(String args[])

    {

        // creating an empty string

        String str = null;

        // print the string length

        System.out.println(str.length());

    }

}

The output is given below.

C:\raji\blog>javac Exception2.java

C:\raji\blog>java Exception2

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>" is null

        at Exception2.main(Exception2.java:8)

These are some of the exceptions in java.

No comments:

Post a Comment