Ad

Exceptional Handling - Java

Exception means abnormal condition also known as runtime errors, it terminates program abnormal in between the execution of the program, So to handle runtime errors we use Exceptional handling.

Some Built-in Java Exceptions handling classes:
  1. ArithmeticException: Arithmetic error, such as divide by zero.
  2. ArrayIndexOutOfBoundsException: Array index is out of bounds.
  3. ArrayStoreException: Assignment to an array element of an incompatible type.
  4. NullPointerException: Invalid use of a null reference.
  5. NumberFormatException: Invalid conversion of a string to a numeric format.
  6. StringIndexOutOfBoundsException: attempt to index outside the bounds of a string.
  7. ClassNotFoundException: Class not found.
  8. IndexOutOfBoundsException:
  9. IOException:
  10. SQLException:

To handle exceptions we use:

  1. try - catch
  2. try - multiple catch
  3. try - catch - finally
  4. try - finally
  5. throw and throws keywords
try - catch block

Example 1: Java Exceptional handling, ArithmeticException, Divide by 0.

package divisionmethod;
// find division of two numbers using method
public class Divisionmethod {
    public static void main(String[] args) {
        try{
            int a=10, b=0, c;
            c=a/b;
            System.out.println("Division = " + c);
        }
        catch(ArithmeticException ex)
        {
            System.out.println("Cannot divide by 0");
        }
    }
}
Run 1:
Cannot divide by 0

Run 2: change value of b with 2, than run
Division = 5
throws keyword

Example 2: Java Exceptional handling, ArithmeticException, Divide by 0.

package divisionmethod;
// find division of two numbers using method
public class Divisionmethod {
    public void division(int a,int b) throws ArithmeticException
    {
        int d = a/b;
        System.out.println("Division = " + d);   
    }
    public static void main(String[] args) {
        Divisionmethod m = new Divisionmethod();
        try{
            m.division(4, 0);
        }
        catch(ArithmeticException ex)
        {
            System.out.println("Cannot divide by 0, ArithmeticException found");
        }
    }
}
Cannot divide by 0