The Nuts and Bolts of the Java Language |
The declaration for themain
method in the character-counting program has an interesting clause shown here in bold:This clause specifies that thepublic static void main(String[] args) throws java.io.IOExceptionmain
method can throw throw an exception calledjava.io.IOException
. So, what's an exception? An exception is an event that occurs during the execution of program that prevents the continuation of the normal flow of instructions. For example, the following code sample is invalid because it tries to divide 7 by 0, which is an undefined operation.The divide by zero operation is an exception because it prevents the code from continuing. Different computer systems handle exceptions in different ways; some more elegantly than others. In Java, when an error occurs, such as the divide by zero above, the program throws an exception. You can catch exceptions and try to handle them within a special code segment known as an exception handler.int x = 0; int y = 7; System.out.println("answer = " + y/x);In Java, a method must specify the "checked" (non-runtime) exceptions, if any, it can throw. This rule applies to the
main
method in our example. Thus thethrows
clause in the method's signature.You may have noticed that the
main
method does not throw any exceptions directly. But it can throw ajava.io.IOException
indirectly through its call toSystem.in.read
.This has been a brief introduction to exceptions in Java. For a complete explanation about throwing, catching, and specifying exceptions refer to Handling Errors Using Exceptions.
The Nuts and Bolts of the Java Language |