Share on Google+Share on Google+

Exception Handling

Advertisement
Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution

Exception Handling

     

Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution. During the program execution if any error occurs and you want to print your own message or the system message about the error then you write the part of the program which generate the error in the try{} block and catch the errors using catch() block. Exception turns the direction of normal flow of the program control and send to the related catch() block. Error that occurs during the program execution generate a specific object which has the information about the errors occurred in the program.

In the following example code you will see that how the exception handling can be done in java program. This example reads two integer numbers for the variables a and b. If you enter any other character except number ( 0 - 9 ) then the error is caught by NumberFormatException object. After that ex.getMessage() prints the information about the error occurring causes.

Code of the program : 

import java.io.*;

public class exceptionHandle{
  public static void main(String[] args) throws Exception{
    try{
      int a, b;
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      a = Integer.parseInt(in.readLine());
      b = Integer.parseInt(in.readLine());
    }
    catch (NumberFormatException ex){
      System.out.println(ex.getMessage() + " is not a numeric value.");
      System.exit(0);
    }
  }
}

Output of this program:

C:\vinod\xml>javac exceptionHandle.java

C:\vinod\xml>java exceptionHandle

For input string: "" is not a numeric value.

Advertisements

Posted on: April 17, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.

Discuss: Exception Handling  

Post your Comment


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