[3206] in java-interest
Re: Better way to handle user-defined exception
daemon@ATHENA.MIT.EDU (Thomas Ball)
Thu Nov 2 22:33:11 1995
Date: Thu, 2 Nov 1995 17:23:58 -0800
From: Thomas.Ball@Eng.Sun.COM (Thomas Ball)
To: edith@pencom.com
Cc: java-interest@java.Eng.Sun.COM
> OK. Now back to my original question. I still need a dummy exception,
> OutOfRangeException which has no code at all because I don't want to show
> user the thread stack (by calling super(mesg) in a constructor) and I would
> like to have a separate method to handle the error message.
>
> I might end up with something like
>
> main()
> {
>
> try
> {
> ....
> ....
>
> }
> catch (dummyException1 e)
> {
> printErrMesg("invalid ID. Please try again.");
> ...
> }
> catch (dummyException2 e)
> {
> printErrMesg("Please enter a whole number for the age field.");
> ....
> }
> catch (dummyException3 e)
> {....}
> .
> .
> .
>
> There must be a better way to handle this. The reason why I insist
> having printErrMesg to hanlde the error message is because I might want
> to print error to System.in, to the status bar of a browser, to the network
> stream, to a popup windows......
>
> Any good suggestion?
Off the top of my head, I'd create a base class that specific exceptions
all subclass from, which defines an error reporter:
class MyBaseException extends Exception {
private String errText;
MyBaseException(String errText) {
this.errText = errText;
}
void printErrMsg() {
System.out.println(errText);
}
}
class dummyException1 extends MyBaseException {
dummyException1() {
super("invalid ID. Please try again.");
}
}
class dummyException2 extends MyBaseException {
dummyException2() {
super("Please enter a whole number for the age field.");
}
}
void main() {
try {
....
....
}
catch (MyBaseException e) {
e.printErrMsg();
}
}
This shows how object-oriented design pays off. You can define a
single behavior for all of your application's exceptions -- if you want
to change printErrMsg, you do it in one place. You also can catch all
your exceptions with one catch statement, since all of your exceptions
are instances of a common base class. (If you want to check for a
specific exception, put its catch block ahead of the more general one.)
Hopefully this is enough to get you started. If you are still having
problems with this, let's take this off-line. Okay?
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