Showing posts with label exception handling. Show all posts
Showing posts with label exception handling. Show all posts

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

Exception handling overview in Java

An exception is an abnormal condition that disrupts normal program flow. There are many cases where abnormal conditions happen during program execution, such as the following:
  1. The file you try to open may not exist.
  2. The class file you want to load may be missing or in the wrong format.
  3. The other end of your network connection may be disrupted for some mysterious reason.
  4. An operand is not in the legal range prescribed for operations or methods.

If these abnormal conditions are not prevented or at least handled properly, either the program will be aborted abruptly or the incorrect results or status will be carried on, causing more and more abnormal conditions. Imagine a program that reads from an unopened file and does computations based on those input values.

Search Techno Talk

Google Groups
Subscribe to Techno Talk
Email:
Visit this group