Sunday, February 04, 2007

Managing exceptions

When we call a method that can throw an Exception, handling the Exception is not the only option we have. We can also propogate the exception. The audio and code shown below explains this concept.





















import java.io.*;

public class AnExceptionalDilemna {
  public static void main(String args[]) {
    AnExceptionalDilemna aed = new AnExceptionalDilemna();
    System.out.println("Hello, this is a test program to
    understand Exceptions");
    try {
      System.out.print("Please enter your name: ");
      String name = aed.getNameThroughMiddleMan();
      System.out.println("Hey "+name+" how are you doing?");
    } catch(IOException ioe) {
      System.out.println("Looks like the standard input
      stream does not like you!");
    }
  }

  /*Do I handle or propogate IOException?
  I do not know what to do with it...
  so I guess I will just pass the buck*/
  private String getNameThroughMiddleMan() throws IOException{
    String name = getName();
    return name;
  }

  private String getName() throws IOException {
    BufferedReader br = new BufferedReader
    (new InputStreamReader(System.in));
    return(br.readLine());
  }
}



Java2html

No comments: