can't throw

B

bob smith

Am I the only one who wanted to throw an Exception but couldn't because I was overriding
a method that threw nothing?

In particular, I'm subclassing Thread and can't throw an Exception in the run method. I suspect this is a more general issue though.
 
M

markspace

Am I the only one who wanted to throw an Exception but couldn't
because I was overriding a method that threw nothing?

In particular, I'm subclassing Thread and can't throw an Exception in
the run method. I suspect this is a more general issue though.

Not really. Either modify the signature of the parent class, or throw a
subclass of RuntimeException. Easy-peasy.

Never throw RuntimeException directly; it'll mean nothing to you or
anyone else reading a stack trace. Always throw some subclass with a
meaningful type.
 
E

Eric Sosman

Am I the only one who wanted to throw an Exception but couldn't because I was overriding
a method that threw nothing?

Happens all the time.
In particular, I'm subclassing Thread and can't throw an Exception in the run method. I suspect this is a more general issue though.

The usual answer is to throw some kind of RuntimeException,
with the original Exception as its "cause." For example,

void method() { // no "throws"
try {
somethingThatCanThrow();
} catch (IOException ex) {
throw new IllegalStateException(
"Fertilizer on fan", ex);
}
}

IllegalArgumentException and IllegalStateException are the
wrappers I find myself using most; there are plenty of others,
and of course you can implement your own RuntimeException subclass
if nothing seems suitable to the situation.

Some people, deeper thinkers than I, consider the whole
business of checked exceptions a nuisance or a misfeature. The
need for a dodge like the above can be seen as evidence for
that viewpoint, but I don't find it overwhelmingly convincing.
In any event, that's Java As It Is And Is Likely To Remain, so
we've got to get used to it whether we sneer at it or not.
Personally, I find it helpful that the compiler reminds me when
I've forgotten to deal with a checked exception; the inconvenience
of wrapping checked in unchecked exceptions seems a minor matter.
 
L

Lew

If you're talking about a checked exception, yes.

If an overridden method throws a check exception not thrown by its
parent implementation, it would break code that calls the method through
the parent type.

As markspace points out, this is not a problem with unchecked exceptions.

Well, duh.

The issue is you aren't supposed to break code that uses the parent type.
Not really. Either modify the signature of the parent class, or throw a
subclass of RuntimeException. Easy-peasy.

Never throw RuntimeException directly; it'll mean nothing to you or
anyone else reading a stack trace. Always throw some subclass with a
meaningful type.

And meaningful message.
 
L

Lew

Eric said:
Happens all the time.


The usual answer is to throw some kind of RuntimeException,
with the original Exception as its "cause." For example,

void method() { // no "throws"
try {
somethingThatCanThrow();
} catch (IOException ex) {
throw new IllegalStateException(
"Fertilizer on fan", ex);
}
}


IllegalArgumentException and IllegalStateException are the
wrappers I find myself using most; there are plenty of others,
and of course you can implement your own RuntimeException subclass
if nothing seems suitable to the situation.

Some people, deeper thinkers than I, consider the whole
business of checked exceptions a nuisance or a misfeature. The

Those people are mistaken.
need for a dodge like the above can be seen as evidence for
that viewpoint, but I don't find it overwhelmingly convincing.

Not even suggestive, much less convincing.
In any event, that's Java As It Is And Is Likely To Remain, so

and for good reason.
 
M

markspace

In particular, I'm subclassing Thread and can't throw an Exception in
the run method. I suspect this is a more general issue though.


I missed "I'm subclassing Thread" earlier. Yes, it is a general issue.
In general, use an Executor, and separate the work to do (a "task" or
Runnable/Callable) and the Thread. They're two different things,
really, and you shouldn't try to combine them or need to subclass Thread
at all.

Executors seem complicated when you read the docs but really they're
very simple to use and provide a lot of capability that would be tough
to try to do on your own.

<http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html>

Don't over look Executors or ExecutorService mentioned in those docs.
 
A

Arne Vajhøj

Am I the only one who wanted to throw an Exception but couldn't because I was overriding
a method that threw nothing?

In particular, I'm subclassing Thread and can't throw an Exception in the run method. I suspect this is a more general issue though.

You are not the first with that problem.

My take is:
* if the API is well designed the the intent must be that the class
is supposed to handle the problems and not throw an exception
at all, and you should follow that guideline
* if the API is not well designed and someone just forgot about
exceptions, then you must consider what is best:
- change the API with all the problems arising from that
- throw a runtime exception

Arne
 
A

Arne Vajhøj

Those people are mistaken.


Not even suggestive, much less convincing.


and for good reason.

I must admit that personally I like the checked exception
context.

But given that languages invented after Java chose not to
implement checked exceptions, then we must conclude that
it has not caught on.

(primarily thinking of C# and Scala here)

So the benefits are not that obvious to everyone.

Arne
 
R

Robert Klemme

Am I the only one who wanted to throw an Exception but couldn't
because I was overriding a method that threw nothing?

In particular, I'm subclassing Thread and can't throw an Exception in
the run method. I suspect this is a more general issue though.

Why are you subclassing Thread in the first place?

Kind regards

robert
 
G

Gene Wirchenko

[...]
But given that languages invented after Java chose not to
implement checked exceptions, then we must conclude that
it has not caught on.

(primarily thinking of C# and Scala here)

So the benefits are not that obvious to everyone.

And more to the point, those other languages do not seem to suffer greatly,
if at all, from the lack of checked exceptions.

For whatever reason, I've never found checked exceptions a compelling
feature. It's absolutely in the right spirit, one which I agree
wholeheartedly with. And yet I find that at least in the Java
implementation, it seems to create more headaches than it prevents.

To me, it also seems as if it would be a good idea, but using it
is awkward. In some coursework, I used a Java cryptographic system.
It had a lot of exceptions to handle so my code had a lot of catches.
Because I did not know what was thrown, I wrote my code without them
and then added whatever the compiler stated was missing. In those
catches, there really was not anything that I could do other than
reporting the error.

I prefer reading the main flow of execution as a high-level
story. Catches interrupt this. When there are a lot of catches, they
make the main code harder to find.
I realize I'm in the minority here. But it's a viewpoint I feel needs to
be expressed.

Thank you.

Sincerely,

Gene Wirchenko
 
R

Robert Klemme

To me, it also seems as if it would be a good idea, but using it
is awkward. In some coursework, I used a Java cryptographic system.
It had a lot of exceptions to handle so my code had a lot of catches.
Because I did not know what was thrown, I wrote my code without them
and then added whatever the compiler stated was missing. In those
catches, there really was not anything that I could do other than
reporting the error.

Well, but that's a valid way to handle an exception. :)
I prefer reading the main flow of execution as a high-level
story. Catches interrupt this. When there are a lot of catches, they
make the main code harder to find.

I my experience that can at least partially be attributed to people
putting several try catch blocks in a method or not making them the
outermost "bracket" of the method. I frequently see a return after the
closing bracket or such thing which makes it harder to read (and decide
what happens in case of error and OK) and - more importantly -
impossible for the compiler to catch control flow errors (e.g. the final
return returns true while in case of error you wanted to return false).

Kind regards

robert
 
J

Jim Janney

Peter Duniho said:
[...]
But given that languages invented after Java chose not to
implement checked exceptions, then we must conclude that
it has not caught on.

(primarily thinking of C# and Scala here)

So the benefits are not that obvious to everyone.

And more to the point, those other languages do not seem to suffer greatly,
if at all, from the lack of checked exceptions.

For whatever reason, I've never found checked exceptions a compelling
feature. It's absolutely in the right spirit, one which I agree
wholeheartedly with. And yet I find that at least in the Java
implementation, it seems to create more headaches than it prevents.

I realize I'm in the minority here. But it's a viewpoint I feel needs to
be expressed.

The major problem I had with checked exceptions was fixed in Java 1.4,
when they introduced a standard way to wrap exceptions without losing
the original stack trace. Java 7 lets you handle all the bogus
exceptions in a single catch clause, so there's a minor nuisance gone.

And if you really need it, there's always

public static void throwChecked(final Exception e) {
class Thrower {
public Thrower() throws Exception {
throw e;
}
}

try {
Thrower.class.newInstance();
} catch (InstantiationException e1) {
throw new RuntimeException(e1); // bogus exception: cannot happen
} catch (IllegalAccessException e1) {
throw new RuntimeException(e1); // bogus exception: cannot happen
}
}

Not that I recommend doing this, but it *is* possible...
 
M

markspace

I prefer reading the main flow of execution as a high-level
story. Catches interrupt this. When there are a lot of catches, they
make the main code harder to find.


Well true, but these sorts of things yield easily to a little thought
and planning.

Given some method or collection of methods that throw a lot of
exceptions, throwsALot(), you can just separate out the exception
handling from the rest of the code.

private void implementation()
throws This, That, Another
{
throwsALot();
}

public void handlers() {
try {
implementation();
} catch( This ex ) {
} catch( That ex ) {
} catch( Another ex ) {
}

Now at least your bothersome exception handling is separate from your
implementation, and you can read the code a bit more easily. One
exception in Java 7 is probably AutoClosable, which you should probably
take advantage of when available.
 
B

bob smith

Why are you subclassing Thread in the first place?



Kind regards



robert



--

remember.guy do |as, often| as.you_can - without end

http://blog.rubybestpractices.com/

There are two ways to create a new thread of execution. One is to declare aclass to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated andstarted. For example, a thread that computes primes larger than a stated value could be written as follows:

class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}

public void run() {
// compute primes larger than minPrime
. . .
}
}

The following code would then create a thread and start it running:

PrimeThread p = new PrimeThread(143);
p.start();
 
E

Eric Sosman

There are two ways to create a new thread of execution. [...]

A splendid explanation! May I have your permission to quote it?
(I'll cite you as the original author, naturally).
 
L

Lew

bob said:
There are two ways to create a new thread of execution. One is to declare a class to be a subclass of

There are far more than two ways.
Thread. This subclass should override the run method of class Thread. An instance of the subclass
can then be allocated and started. For example, a thread that computes primes larger than a stated
value could be written as follows:

Are you quoting something here?

You explained what you're doing, but you didn't answer Robert's question of why.

Why are you subclassing Thread in the first place?

It's abnormal and you aren't doing anything that obviously calls for this idiom.

"Because I can!" only answers a certain question asked of a male dog.
 
A

Arne Vajhøj

Why are you subclassing Thread in the first place?

If he thinks his class is-a Thread, then why not.

And implementing Runnable would not avoid the problem anyway.

Arne
 
D

Daniel Pitts

there is no point in throwing from Thread.run()
or Runnable.run() other than catastrophic failures (all Errors such as
OOM, all RuntimeExceptions which are really programmer mistakes) because
you cannot customize handling of exceptions thrown from the run()
method: this method is only invoked from class Thread and probably
others in the Java standard library itself.
Actually, you can handle exceptions from a Thread. There is the
UncaughtExceptionHandler:
<http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.UncaughtExceptionHandler.html>

Though the only valuable use I have ever seen from this is in logging
those failures differently than the default output.
Instead, you should be
handling exceptions in run() and terminate the thread gracefully (i.e.
by returning from run()).

Agreed. If you need some other code to propagate an Exception, you need
to pass that information along. Exceptions are meant to unwind the
stack. For most practical purposes a Thread's run() method really has no
stack to unwind. Even if you could throw an Exception from it, where
would that Exception go? Who's going to deal with it?
 
A

Arne Vajhøj

You are not the first with that problem.

My take is:
* if the API is well designed the the intent must be that the class
is supposed to handle the problems and not throw an exception
at all, and you should follow that guideline
* if the API is not well designed and someone just forgot about
exceptions, then you must consider what is best:
- change the API with all the problems arising from that
- throw a runtime exception

Specifically about the Thread and run case: what would be
the point in throwing an exception? What code should do
something about it?

(well - I guess Thread.setDefaultUncaughtExceptionHandler can
be used, but it is not going to be pretty)

Arne
 
A

Arne Vajhøj

I must admit that personally I like the checked exception
context.

It makes a lot of sense if you are API centric.

A contract "I will either return a value of type X or throw
one of the exceptions E1,...,En" seems a lot more strict than
"I will either return a value of type X or throw an exception
but I will not tell you which".

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top