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 is an Exception?
Consider this program:
public class HelloThere {
public static void main(String[] args) {
System.out.println("Hello " + args[0]);
}
}
Suppose it's run like this:
% java HelloThere
Notice that's there's no args[0] . Here's what you get:
% java HelloThere
java.lang.ArrayIndexOutOfBoundsException: 0
at HelloThere.main(HelloThere.java:5)
This is not a crash. The virtual machine exits normally.
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. |