try-catch

try-catch

public class HelloThere {

  public static void main(String[] args) {
  
    try {
      System.out.println("Hello " + args[0]);
    }
    catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Hello Whoever you are.");
    }
  
  }

}

What can you do with an exception once you've caught it?

  1. Fix the problem and try again.
  2. Do something else instead.
  3. Exit the application with System.exit()
  4. Rethrow the exception.
  5. Throw a new exception.
  6. Return a default value (in a non-void method).
  7. Eat the exception and return from the method (in a void method).
  8. Eat the exception and continue in the same method (Rare and dangerous. Be very careful if you do this. Novices almost always do this for the wrong reasons. Do not simply to avoid dealing with the exception. Generally you should only do this if you can logically guarantee that the exception will never be thrown or if the statements inside the try block do not need to be executed correctly in order for the following code to run.)

Printing an error message by itself is generally not an acceptable response to an exception.


Previous | Next | Top | Cafe au Lait

Copyright 1999, 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 1, 2000