Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language


Introducing Exceptions

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.");
    }
}    
The following code snippet is invalid because it tries to divide 7 by 0 and mathematically divide by 0 is an undefined operation.
int x = 0;
int y = 7;
System.out.println("answer = " + y/x);
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.

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 called java.io.IOException. You will notice that the main() method does not throw any exceptions directly. Rather it can throw one indirectly through its call to System.in.read().

See Also

Error Handling and Exceptions


Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language