[2394] in java-interest
Re: throws declataration in Java/beta
daemon@ATHENA.MIT.EDU (Thomas Ball)
Sat Sep 30 08:11:17 1995
Date: Thu, 28 Sep 1995 09:48:29 -0700
From: tball@alapa@sun.com (Thomas Ball)
To: garya@village.org
Cc: java-interest@java@sun.com
> >> >It is very important to realize that a Java class is a guaranteed interface.
> >> >If an method is declared to throw a certain set of exceptions than there is no
> >> >way a sub class can change that. At first this may seem restrictive, but after
> >> >a while you will realize that it is wonderful to have this guarantee.
> >>
> >> It's not clear to me what's so wonderful about this guarantee.
> >> There is no similar guarantee that a subclass will not compromise the intended
> >> behavior of its base in numerous other ways. What makes exceptions special?
> >
> >Exceptions affect the control flow of the caller. While implementing
> >this feature we found a number of bugs in HotJava were we simply didn't
> >realize that a certain exception could thrown.
>
> In other words, because the particular piece of code you were working on
> did not properly handle all the possible exceptions in the code it called,
> and this caused some (understandable :-)) debug problems, the decision was
> made to disallow throwing an exception of a different type.
>
> This seems like the wrong approach. Wouldn't it be much more useful to
> require the equivalent of a C++/C switch stmt "default" catch clause in
> all exception situations? That would allow for a subclass to throw and
> catch additional exceptions, and also require that the caller be prepared
> to at least be made aware that some unforseen exception has occurred and
> was not handled.
You forget, Gary, that all exceptions are subclassed from Exception.
It's quite acceptable to have multiple catch blocks going from more
specific to least, as in:
try {
Socket s = new ServerSocket(port, 10).accept();
DataInputStream in = new DataInputStream(
new BufferedInputStream(s.getInputStream()));
String ln;
while ((ln = in.readUTF()) != null) {
...
}
} catch (UTFDataFormatException utfe) {
// very specific: client failure?
} catch (IOException ioe) {
// somewhat specific: connection problem?
} catch (Exception e) {
// generic: unknown exception
e.printStackTrace();
System.exit(1);
}
Essentially, the "catch (Exception e)" is your default catch phrase.
Tom
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com