The Nuts and Bolts of the Java Language |
The following code snippet is invalid because it tries to divide 7 by 0 and mathematically divide by 0 is an undefined operation.class Count { public static void main(String args[]) throws java.io.IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has " + count + " chars."); } }An event that occurs during the execution of program that prevents the continuation of the normal flow of instructions, such as the divide by 0 above, is called an exception. Different computer systems handle exceptions in different ways; some more elegantly than others.int x = 0; int y = 7; System.out.println("answer = " + y/x);In the Java language, you can catch exceptions and try to handle them within a special code segment known as an exception handler. The exception handler can try to recover from the error, or if the error is too serious to recover from, then the exception handler can display pertinent information to help the user detect the problem.
In the Java language, every method must declare all of the exceptions, if any, it can throw. The bold line shown in the character-counting application above declares that the
main()
method can throw an exception calledjava.io.IOException
. You will notice that themain()
method does not throw any exceptions directly. Rather it can throw one indirectly through its call toSystem.in.read()
.See Also
Error Handling and Exceptions
The Nuts and Bolts of the Java Language |