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?
- Fix the problem and try again.
- Do something else instead.
- Exit the application with
System.exit()
- Rethrow the exception.
- Throw a new exception.
- Return a default value (in a non-void method).
- Eat the exception and return from the method (in a void method).
- 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
Last Modified January 1, 2000
Copyright 1999, 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu