[3190] in java-interest

home help back first fref pref prev next nref lref last post

Re: Better way to handle user-defined exception

daemon@ATHENA.MIT.EDU (Thomas Ball)
Thu Nov 2 20:12:12 1995

Date: Thu, 2 Nov 1995 14:18:17 -0800
From: Thomas.Ball@Eng.Sun.COM (Thomas Ball)
To: edith@pencom.com
Cc: java-interest@java.Eng.Sun.COM

>   The following "code" will throw a user-defined exception if
> 
> user entered a number < 0 or > 10.
> 
> class abc
> {
> 
>   public static void main(String args[]) throws 
> outOfRangeException
>   {
>     try
>     {
>       int x = new Integer(args[0]).intValue();
>       if (x < 0 || x > 10)
> 	throw new outOfRangeException();
>     }
>     catch (NumberFormatException e)
>     {
>       printErrMesg("Wrong format");
>     }
>     catch (outOfRangeException e)
>     {
>       printErrMesg("Out of range input");
>     }
>   }
> 
>   static void printErrMesg(String mesg)
>   {
>     System.out.println(mesg);
>   }
> }
> 
> 
> class outOfRangeException extends Exception
> {
>   outOfRangeException()
>   {}
> }
> 
> 
> From the user friendly point of view, I don't want to show user
> a thread stack if an out of range number is entered.  I just
> want to print out a simple error message.  I am forced to 
> create a dummy exception subclass, outOfRangeException, because
> I want to catch the exception in the main program. 

You are not forced to do anything -- the decision whether to use or
not use user-defined exceptions is yours to make.  I wouldn't use it
in your example above.
 
>   You might argue I can just simply do
> 	if (x<0 || x>10)
> 	  System.out.println ("Out of Range Input.");
> 
> but that's not what I want.  I would like to have a centralize
> place (method printErrMesg()) to handle error message.

Then just do:
	if (x<0 || x>10)
	  printErrMessage("Out of Range Input.");

> Does anyone has a better way to handle this?  Creating a dummy
> exception is kind of ugly and confused.........

I think your confusion stems from not fully understanding how to use
exceptions -- it's a new concept for many programmers, so please don't
take my comment as a criticism.  Exceptions are useful for separating
correct program execution from error handling -- it makes for easier to
read code if used properly, as well as fewer ignored error conditions.
Several recent C++ books discuss exception handling for people who are
new to the concept -- can someone else recommend such a book?

Tom Ball
Java Products Group
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post