Why shouldn't we catch class RuntimeException?

K

kaja_love160

Hello

Book I’m learning from claims that exceptions of type RuntimeException
and its children are thrown due to bad programming and should be
avoided by writing better code. One such exception of type
RuntimeException might happen when a user is asked to enter a value
and user enters an invalid value  this may cause runtime exception.
We can go about it in two ways:

1) by writing "if ( correct input ) .. else"
2) or by throwing and catching an exception

Now according to my book ( as I understood it ) we should use
something like : if ( correct input ) .. else “ to deal with this
problem and not use exceptions. Why shouldn’t exceptions be used for
such cases?

Thank you
 
B

Ben Schumeth

Hello

Book I’m learning from claims that exceptions of type RuntimeException
and its children are thrown due to bad programming and should be
avoided by writing better code.

Please throw that book out the window, preferably onto the writer's head.
One such exception of type
RuntimeException might happen when a user is asked to enter a value
and user enters an invalid value  this may cause runtime exception.
We can go about it in two ways:

1) by writing "if ( correct input ) .. else"
2) or by throwing and catching an exception

Now according to my book ( as I understood it ) we should use
something like : if ( correct input ) .. else “ to deal with this
problem and not use exceptions. Why shouldn’t exceptions be used for
such cases?

There are many possible reasons why, in specific cases, one may be better
than the other. Take the following:

String getInput()
{
// get input from the user and return it
}

void showOutput( String output )
{
// show output to the user
}

void doSomething()
{
String theInput = getInput();
// process the input
}

A reasonable approach would be to have getInput just get the input,
without checking its validity. Then, doSomething could use the if/else
case: it checks the input, and if it is invalid notifies the user.
Alternatively, getInput could do some error checking. Now, if the user
gives invalid input, what should getInput do? It might tell the user that
the input is incorrect and ask new input. Fine, but what if getInput
doesn't know how to show output since that is showOutput's task? (note:
getInput and showOutput could be methods of different classes) getInput
knows how to get input, but it has no idea where output should go, what
format it should have, ... In that case it is perfectly reasonable to
have getInput throw a RuntimeException, and have doSomething catch that
exception and handle it as required.
This is a very simple and somewhat contrived example (input and output are
typically linked, if only to give the user some indication that input is
expected - plus, incorrect user input is hardly exceptional so it may not
be a perfect candidate for Exception usage); there are however countless
reasons why RuntimeExceptions can be useful.

In the book's defence, it was probably talking about NullPointerException,
ClassCastException, IllegalArgumentException, etc. which can - in many
cases - indeed be avoided.

Ben
 
R

Robert Klemme

Book I’m learning from claims that exceptions of type RuntimeException
and its children are thrown due to bad programming and should be
avoided by writing better code. One such exception of type
RuntimeException might happen when a user is asked to enter a value
and user enters an invalid value  this may cause runtime exception.
We can go about it in two ways:

1) by writing "if ( correct input ) .. else"
2) or by throwing and catching an exception

Now according to my book ( as I understood it ) we should use
something like : if ( correct input ) .. else “ to deal with this
problem and not use exceptions. Why shouldn’t exceptions be used for
such cases?

Usually the front end is considered responsible for making sure only
proper data enters the system. That way you can prompt the user with a
much more meaningful error message. It's double checking in a way - but
the class should make sure instance state stays consistent, so usually
setter methods throw if presented illegal data. The UI check should be
there to additionally make sure the user gets informed what he did wrong
("you did not enter a number in field 'ZIP code'" which is better than
an error you might be seeing from the application like "not numeric").

Kind regards

robert
 
T

Tom Hawtin

Book I’m learning from claims that exceptions of type RuntimeException
and its children are thrown due to bad programming and should be
avoided by writing better code. One such exception of type
RuntimeException might happen when a user is asked to enter a value
and user enters an invalid value  this may cause runtime exception.
We can go about it in two ways:

1) by writing "if ( correct input ) .. else"
2) or by throwing and catching an exception

Well, yes and no.

Generally RuntimeExceptions should be used in preference to checked
exceptions where a fault in programming is detectable. Checked
exceptions should be used (and hence caught) when dealing with faults
that occur outside of the system (for some suitable definition of system).

A common example of catching a particular RuntimeException is when using
Integer.parseInt. Shouldn't that NumberFormatException be a checked
exception. Well, the method was intended to be used to pass strings from
known good sources. It clearly isn't designed for user input because
there is no internationalisation.

For user input, we need to go to the java.text package.
Format.parseObject is declared to throw ParseException which is checked.
Note that the opposite Format.format throws an unchecked IllegalArgument
exception if the object is unformattable. That is because the object
should come from an internal source and therefore known to be correct.
If it is not correct, then it is a programming error, not a user typo.

Tom Hawtin
 
K

~kurt

Ben Schumeth said:
Please throw that book out the window, preferably onto the writer's head.

I believe the OP is not understanding that a RuntimeException usually
isn't used for checking IO (that would be an IOException). RuntimeExceptions
are "unchecked" and pretty much always due to a programming error. I can
think of cases where you might want to catch them - but they would still be due
to writing the application wrong.
Alternatively, getInput could do some error checking. Now, if the user
gives invalid input, what should getInput do? It might tell the user that
the input is incorrect and ask new input. Fine, but what if getInput
doesn't know how to show output since that is showOutput's task? (note:
getInput and showOutput could be methods of different classes) getInput
knows how to get input, but it has no idea where output should go, what
format it should have, ... In that case it is perfectly reasonable to
have getInput throw a RuntimeException, and have doSomething catch that
exception and handle it as required.

I think you would want to throw an IOException (checked), not a
RuntimeException. Both are Exceptions, but neither inherits from the
the other.
In the book's defence, it was probably talking about NullPointerException,
ClassCastException, IllegalArgumentException, etc. which can - in many
cases - indeed be avoided.

These are all RuntimeExceptions.

- Kurt
 
L

Lew

~kurt said:
I believe the OP is not understanding that a RuntimeException usually
isn't used for checking IO (that would be an IOException). RuntimeExceptions
are "unchecked" and pretty much always due to a programming error. I can
think of cases where you might want to catch them - but they would still be due
to writing the application wrong.

This seems like an extremely potent argument in favor of catching and logging
such exceptions. A programmer should know when they err.
I think you would want to throw an IOException (checked), not a
RuntimeException. Both are Exceptions, but neither inherits from the
the other.

The question of whether to throw a checked or unchecked Exception is subtle
and controversial. Thee suggestion to throw a RuntimeException for programmer
errors and a checked Exception for data or user errors made sense to me.
These are all RuntimeExceptions.

But they aren't all the RuntimeExceptions.

There are two discussions here - whether to catch RuntimeExceptions and
whether to throw them. I'm in favor of both, under the right circumstances.
 
P

Patricia Shanahan

Lew said:
The question of whether to throw a checked or unchecked Exception is
subtle and controversial. Thee suggestion to throw a RuntimeException
for programmer errors and a checked Exception for data or user errors
made sense to me.

I take a slightly different philosophy, though I think it leads to the
same answers.

If the risk of an exception is pervasive in the application, so that
most methods would have to deal with it, then it should be unchecked,
and presumed to be a possibility throughout the application. Making
SomeException extend RuntimeException is a less verbose equivalent of
sticking "throws SomeException" on every method.

If the risk of the exception is localized, so that some methods will
have to deal with it and other can be written assuming they will never
see it, then it should be checked, to make sure the right methods handle it.

Patricia
 
K

~kurt

Lew said:
This seems like an extremely potent argument in favor of catching and logging
such exceptions. A programmer should know when they err.

But, such exceptions will abort the application, and leave a trace to where
the abort came from. Many of them can't really be dealt with.

Lets say you have a mathematical model that does matrix and vector
multiplication? If you attempt to multiply two matrices whose dimensions
don't match, then the application might as well just abort because your
math is wrong. There is no way to recover.

If, however, those matrices where formed from some type of interactive
user interface - then catching the abort would be worthwhile because then
you could inform the user of the mistake, and he could try again. But, the
application probably should have checked the dimensions in the first place....

I guess if the mathematical model was in a video game, then you could have
whatever it is you are modeling revert to some default state if you
catch the exception - it would make things look better to the end user.
But they aren't all the RuntimeExceptions.

NullPointerException, ClassCastException, and IllegalArgumentException
are.
There are two discussions here - whether to catch RuntimeExceptions and
whether to throw them. I'm in favor of both, under the right circumstances.

Yea - I was just dealing with the issue recently, which is why the
thread caught my attention. So far implementation is working well so
I guess that means I made the right choice in this situations....

My assumption was that the OP didn't understand the difference between
a checked and unchecked exception, and that was leading to some
confusion.

- Kurt
 
L

Lew

~kurt said:
But, such exceptions will abort the application, and leave a trace to where
the abort came from. Many of them can't really be dealt with.

What?

Huh?

I said "catching and logging". There is no "abort the application" there.

All of them can be dealt with. Why do you think otherwise?
Lets say you have a mathematical model that does matrix and vector
multiplication? If you attempt to multiply two matrices whose dimensions
don't match, then the application might as well just abort because your
math is wrong. There is no way to recover.

Of course there is.
If, however, those matrices where formed from some type of interactive
user interface - then catching the abort would be worthwhile because then
you could inform the user of the mistake, and he could try again. But, the
application probably should have checked the dimensions in the first place....

This is a program bug, yes.
I guess if the mathematical model was in a video game, then you could have
whatever it is you are modeling revert to some default state if you
catch the exception - it would make things look better to the end user.

These types of exceptions shouldn't occur in production code, but if they do,
it's useful to know it, and not have the application crash, which is why you
catch them.
NullPointerException, ClassCastException, and IllegalArgumentException
are.

But they aren't - there are many others as well. For example,
UnsupportedOperationException, and that's just in java.lang! I'm not even
looking at all the standard API, much less all the code everyone is writing.
The set of RuntimeExceptions is likely growing as we speak. How can you say
that those three are all the RuntimeExceptions?
 
M

manivannan.palanichamy

What?

Huh?

I said "catching and logging". There is no "abort the application" there.

All of them can be dealt with. Why do you think otherwise?


Of course there is.


This is a program bug, yes.


These types of exceptions shouldn't occur in production code, but if they do,
it's useful to know it, and not have the application crash, which is why you
catch them.



But they aren't - there are many others as well. For example,
UnsupportedOperationException, and that's just in java.lang! I'm not even
looking at all the standard API, much less all the code everyone is writing.
The set of RuntimeExceptions is likely growing as we speak. How can you say
that those three are all the RuntimeExceptions?

Good programming practice assumes that you have already validated
input data, and as well written 'catch' to catch what can probably go
wrong at runtime. One cannot list out all the million possible
scenarios of failure at runtime. Thats why, almost every possible
'worse' is already defined under 'Checked Exceptions'. Anything that
falls out of the 'Checked Exception' category is 'too worse' -- thats
RuntimeException. Your code should terminate as soon as the 'too
worse' (RuntimeException) happens.

But, who stops us, from handling the 'too worse'? :) If one has the
stamina, then can very well catch up the RuntimeException!
 
L

Lew

Good programming practice assumes that you have already validated

However, /great/ programming practice assumes nothing and protects against
everything. Least of all does it assume one's own perfection as a programmer.
input data, and as well written [sic] 'catch' to catch what can probably go
wrong at runtime.

But that's exactly what I'm saying. Catch the runtime exceptions, where
reasonable. Of course, I mean to say use a "well-written 'catch'".
One cannot list out all the million possible scenarios of failure at runtime. Thats why, almost every possible
'worse' is already defined under 'Checked Exceptions'.

Statistical assertions need statistical evidence. "Almost every"?
Anything that falls out of the 'Checked Exception' category is 'too worse' -- thats
RuntimeException. Your code should terminate as soon as the 'too
worse' (RuntimeException) happens.

A Web app likely should not terminate, but restore the user to a part of the
app not subject to the bug so that they continue and so that the million other
concurrent users don't suddenly lose their sessions for no apparent (to them)
reason.
But, who stops us, from handling the 'too worse'? :) If one has the
stamina, then can very well catch up the RuntimeException!

I don't know what stamina has to do with it. I suggest one do the analysis
and program for the relevant situations. Sometimes those situations involve
catching RuntimeExceptions; whether they do or not is revealed through the
analysis.
 
K

~kurt

Lew said:
What?

Huh?

I said "catching and logging". There is no "abort the application" there.

All of them can be dealt with. Why do you think otherwise?

Do you use try and catch statements for IndexOutOfBoundsExceptions every
time you access an element of an array? I'm talking about exceptions that
extend RuntimeException.
Of course there is.

It depends on the application. I do modeling and simulation for a living -
There are some applications that you would like to never have blow up
on the users (makes you look bad), and just send a warning message to
the user. Others might as well blow up as there is nothing more that
can be done if the algorithm is bad.
These types of exceptions shouldn't occur in production code, but if they do,
it's useful to know it, and not have the application crash, which is why you
catch them.

Once again, we are talking about RuntimeExceptions. Should we all be
catching array indexing errors?
But they aren't - there are many others as well. For example,
UnsupportedOperationException, and that's just in java.lang! I'm not even
looking at all the standard API, much less all the code everyone is writing.
The set of RuntimeExceptions is likely growing as we speak. How can you say
that those three are all the RuntimeExceptions?

I never said those three are "all the RuntimeExceptions". I said they are
all RuntimeExceptions. Meaning, they are not IOExceptions. Generally,
you do *not* catch RuntimeExceptions. So, the advice given by the book
is not bad. If an exception should be caught, it should not extend
RuntimeException.

I get a feeling that we are not talking about the same thing here, or
misunderstanding each other.

- Kurt
 

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,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top