[2040] in java-interest
Re: throws declataration in Java/beta
daemon@ATHENA.MIT.EDU (Chuck McManis)
Fri Sep 22 07:24:54 1995
Date: Thu, 21 Sep 1995 11:14:07 -0700
From: cmcmanis@scndprsn.Eng.Sun.COM (Chuck McManis)
To: pambrose@weblogic.com, dufourd@enst.enst.fr
Cc: java-interest@java.Eng.Sun.COM
>>This means that you can NEVER throw an exception from a
>>toString() method because Object.toString() doesn't throw
>>any exceptions.
This is true.
>This is my experience too, and this language/compiler design decision
>seems pretty lame to me. Another thing you cannot do is ask for the
>current thread to sleep when you are in the run method because the
>interface Runnable does not specify "throws InterruptedException"...
>I am sure there are lots of other such examples.
this is not true, you can call sleep, you can call anything you want
however if what you call throws an exception you have to catch that
exception and deal with it, you can't let it be thrown from the run()
method. This is the Right Thing to do because clients of run know exactly
what it will throw and what they have to be prepared to deal with.
For example if you are going to sleep in run() (as applets are want to
do) and you get an InterruptedException it means that someone wants you
awake now (probably because they have told your thread to die.) And you
should break out of your loop or what ever. A typical applet
might implement:
public void run () {
while (aniMateThread != null) {
... do some stuff ...
aniMateThread.sleep(500);
}
}
And you would expect that in the stop method of the applet it would go
something like:
public void stop() { aniMateThread = null };
And in general this worked, but we discovered that while the thread was
sleeping, the applet could be stopped and started leaving two running
run instances. (yuck) and sometime the thread would sleep forever! So
now the sleep() method can get InterruptedException to tell it to wake
up. So you rewrite run as :
public void run () {
while (aniMateThread != null) {
... do some stuff ...
try {
aniMateThread.sleep(500);
} catch (InterruptedException e) {
break; // must be they want us to stop
}
}
}
Now we can stop the applet thread in a "friendly" and asynchronous way.
Overall, the requirement to specify and adhere to 'throws' clauses strikes
me the same way prototypes did when they became part of C. They can be
really annoying, but they catch some bugs before they happen, after a while
you don't even notice them.
--Chuck
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com