Home‎ > ‎Applied Core Java‎ > ‎Exception Handling‎ > ‎

Problem : How to handle Exceptions .

Program :

Step 1 - Coding

Create a text file c:\sunilos\Throwdemo.java  and copy below contents.

import java.io.*;

public class Throwdemo
  public static void main(String[] args)throws Exception {
      int a,b;
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
     System.out.println("please input data ");
      a = Integer.parseInt(in.readLine());
      b = Integer.parseInt(in.readLine());
     int result  = division(a,b);        // Line 2
     System.out.println("result : "+result);

    catch(NumberFormatException ex){
     System.out.println(ex.getMessage() + " is not a numeric value.");
  public static int division(int totalSum, int totalNumber) {
      int quotient = -1;
      System.out.println("Computing Division.");
          quotient  = totalSum/totalNumber;

      catch(Exception e){
          System.out.println("Exception : "+ e.getMessage());
          if(quotient != -1){
              System.out.println("Finally Block Executes");
              //System.out.println("Result : "+ quotient);
              System.out.println("Finally Block Executes. Exception Occurred");
              return quotient;

      return quotient;

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy Throwdemo.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile Throwdemo.java with help of 
    • javac Throwdemo.java command. Command will create class file in the same folder.
  5. Congratulations!! your Java program is ready to serve.
Step 3 - Testing
  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java Throwdemo command.

Output :

please input data
For input string: "sa" is not a numeric value.Please insert numeric values only

please input data
Computing Division.
Exception : / by zero
Finally Block Executes. Exception Occurred
result : -1

Again run the Programe
please input data
Computing Division.
Finally Block Executes
result : 50

         1. Which package contain exception handling related classes ?
             ans. java.lang
         2. What is the base class of exception ?
             ans. java.lang.Throwable
         3.  What is difference between Exception and Error in java?
             ans. Exception and Error are the subclasses of throwable classes . Exception class is used  for exception conditions that user prog. should catch. Errror defines exception that are not    expected to be caught by the user prg. example is stack overflow.
        4. What is difference between Throw and Throws ?
            ans. throw is used to explicity raise a exception within the prog., the statement would be throw new Exception ();
                   throws clause is used to indicate the exception that are not handled by the method.
Mahima Hardia,
Mar 10, 2011, 2:53 AM