Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-exception Example to show class exception in java

Related Tutorials


 
 

Share on Google+Share on Google+

Example to show class exception in java

Advertisement
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

     

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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 22, 2008

Related Tutorials

Discuss: Example to show class exception in java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com