Home > DeveloperSection > Articles > Exception Handling in Java: User-defined Exceptions

Exception Handling in Java: User-defined Exceptions


Java Exception Handling  Java 
Ratings:
0 Comment(s)
 164  View(s)
Rate this:

Exception Handling in Java: User-defined Exceptions


Sometimes we may find that the exception messages given by the standard exception classes are not intuitive, and it may be necessary to provide more elaborate messages to the application user.


In some other situations, we may want to capture the application errors and inform the user of them. An application error could simply be an abnormal condition that needs to be reported to the user and would not result in an application shutdown. To illustrate this point, we will develop an application in this section that reports the weather conditions to the user.


Consider the case where a tourist agency sends the enrolled tourists to their desired locations. Once they are on their tour, each one reports the weather condition at their location. The agency simply logs the report sent by each tourist. The current temperature determines the weather condition at that time.

·         If the temperature is more than 60°F, we generate a too-hot exception

·         If the temperature is less than 10°F, we generate a too-cold exception.

·         For the in-between range, no exception is generated.

The implementation of this scenario is shown here:

public class Tourist {

                     public static void main(String[] args) {

                             for (int i = 0; i < 10; i++) {

                                      Tourist person = new Tourist();

                                      try {

                                                 person.takeTour();

                                                 System.out.printf("Tourist %d say: This is cool%n", i + 1);

                                      } catch (TooHotException hx) {

                                                System.out.printf("Tourist %d say: %s%n", i + 1,

                                                                   hx.getMessage());

                                                continue;

                                      } catch (TooColdException hx) {

                                                System.out.printf("Tourist %d say: %s%n", i + 1,

                                                                   hx.getMessage());

                                                continue;

                                      } finally {

                                                System.out.println();

                                      }

                             }

                     }

 

                     void takeTour() throws TooHotException, TooColdException {

                             int temperature = (int) (Math.random() * 100);

                             System.out.println("temperature = " + temperature);

                             if (temperature > 60) {

                                      throw new TooHotException("Too hot here");

                             } else if (temperature < 10) {

                                      throw new TooColdException("Too cold here");

                             }

                     }

 

                     class TooColdException extends Exception {

                             public TooColdException(String message) {

                                      super(message);

                             }

                     }

 

                     class TooHotException extends Exception {

                             public TooHotException(String message) {

                                      super(message);

                             }

                     }

}

 

Besides the main application class Tourist, the program defines two classes:

·         TooColdException

·         TooHotException.

Both these classes extend Exception classes and provide a constructor that takes a String type argument.

·    The Tourist class declares a method called takeTour. The method is declared to throw the two aforementioned exceptions to its caller for it to handle them.

·      In the method, we set the current temperature to a random value in the range of 0 to 100. We check this value against the preset values of 60 and 10.

·    If the temperature exceeds 60°F, we throw an object of TooHotException to the caller using the following statement:

                       if (temperature > 60) {

                                    throw new TooHotException("Too hot here");

Note how the object is constructed. We use the new keyword, as usual, to create the object and then pass this instance to the caller of this method by using the throw keyword. Likewise, if the temperature is lower than 10°F, we throw a TooColdException to the caller.

In the main method, we create 10 tourists, and for each created tourist we call its takeTour method. In the exception handler, we create an appropriate message. In case of no exceptions, we create a “cool weather” message. In each iteration, we print the message and clear the buffer for the next tourist.

Partial output on a sample run of the application is shown here:

temperature = 37

Tourist 1 say: This is cool

temperature = 97

Tourist 2 say: Too hot here

temperature = 97

Tourist 3 say: Too hot here

temperature = 12

Tourist 4 say: This is cool

 


Don't want to miss updates? Please click the below button!

Follow MindStick