Example to show class exception in java

Here we are describing the example to show the use of class exception in java .Exceptions are the way in Java to indicate to a calling method that an abnormal condition has occurred.

Example to show class exception in java

Here we are describing the example to show the use of class exception in java .Exceptions are the way in Java to indicate to a calling method that an abnormal condition has occurred.

Example to show class exception in java

Example to show class exception in java

     

In this Tutorial we are describing the example to show the use of class exception in java .Exceptions are the condition  in Java to indicate a calling method when an abnormal condition has occurred. This tutorial describes  how to use exceptions in your programs.In this program an exception like division of any number by zero,an exception is caught The steps involved in the program are described below:-

result = a / b:-This is the result which is to be displayed or where the calculation is being performed.

catch (ArithmeticException e) { System.out.println(e.getMessage()+"Exception"):-This is the Exception message which is to be displayed if any of the error occured.ArithmeticException" is a subclass of "RuntimeException", which again is a subclass of class "Exception

ClassException.java

public class ClassException {
public float divide(int a, int b) {
  float result;
  try {
  result = a / b;
  }
  catch (ArithmeticException e) {
  System.out.println(e.getMessage()+"Exception");
  result = Float.NaN;
  }
  return result;
}
  public static void main(String[] args) throws Exception {
  ClassException a=new ClassException();
  System.out.println(a.divide(4,0));
  
  }
}

Output of the program

/ by zeroException
NaN

Download source code