Sunday, August 16, 2009

Exception Handling Basic Model

Java follows the basic C++ syntax for exception handling. First, you try to execute a block of statements. If an abnormal condition occurs, something will throw an exception that you can catch with a handler.

In addition there may be a block of statements you always want executed- no matter whether an exception occured and no matter whether the exception is handled if it does occur.

Throwing an exception is friendlier than terminating the program because it provides the programmer with the option of writing a handler to deal with the abnormal condition. For example, the following program fragment causes the program to sleep for 10 seconds (10,000 milliseconds) by calling the sleep() class method defined in class Thread of the java.lang package. If sleep is interrupted before the time expires, a message is printed and the execution cotinues with the statement following this try-catch construct:

PrintWriter out = new PrintWriter(System.out, true);
try{
Thread.sleep(10000);
} catch (InterruptedException e){
out.println("Sleeping Interrupted.");
}
//reaches here after try-block finished or exception handled

No comments:

Post a Comment

Search Techno Talk

Google Groups
Subscribe to Techno Talk
Email:
Visit this group