The philosophy of exception.

Z

zaemin

Hello everyone~

I have a question about the exception of java.

Actually, I knew how it works and how I can use it.

But what I wonder is 'when do I have to use it?'

I think that I can avoid all the situation that the exceptions occurs.

I can avoid the situation that the index of array passes the last
element or some value is divided by zero by checking the variable.

These are what I can do to prevent from zero-division as an example.

1. Avoid zero-division by check the value.
....
if(d != 0)
return a / d;
else
return -1; // Assume this return value indicates an error
simply.
....

2. Avoid zero-division by exception.
....
try{
return a / d;
}catch{ArithmeticException e){
return -1; // Assume this return value indicates an error
simply.
}
...

In java, which one is better?

If there is no exact answer for this kind of situation,
Can anyone give me guides to distinguish when to use 'code checking'
and when to use 'exception'?


Thanks for your considerations.
 
A

Andrew Thompson

...
I think that I can avoid all the situation that the exceptions occurs.

What about when I have renamed the file
your program is trying to read?
 
H

Harald Hein

zaemin said:
But what I wonder is 'when do I have to use it?'

You don't have to, unless, of course you use an API which can throw an
exeption. But that is not the question:
I think that I can avoid all the situation that the exceptions
occurs.

Sure you can. And if you do as you suggest, you clutter all you code
with:

int value = someMethod();
if(value == -1) {
return -1;
}
int value2 = someMethod(value);
if(value2 == -1) {
return -1;
}

1. Avoid zero-division by check the value.
....
if(d != 0)
return a / d;
else
return -1; // Assume this return value indicates an error
simply.

And simply wrong. What do you do with

a = -1;
d = 1;

You can't return that value, because you just decided that -1 is an
error code.
....

2. Avoid zero-division by exception.
....
try{
return a / d;
}catch{ArithmeticException e){
return -1; // Assume this return value indicates an error
simply.

Which is nonsens. If you use exceptions to convert them into an error
code as soon as possible, then you can indeed just check in advance.

A better handling here would have been not to catch the exception, but
instead let it propagate upwards.
In java, which one is better?

Non, because you insist on providing a return code. In the second case
you just use an alibi exception handling to do what you want. Let's
face it. You don't like exceptions, so you are looking for excuses not
to use them.
If there is no exact answer for this kind of situation,
Can anyone give me guides to distinguish when to use 'code
checking' and when to use 'exception'?

As a rule of thumb: You use exeptions for events that usually don't
happen during the normal flow of control. You use tests if the error is
part of the normal operation of a method.

You use exceptions if you want to handle an error on the right
(potentially higher) level in the program.
 
Y

Young Seeker

I have a related question about dealing with exceptions.

In my Java 101 class, I learnt that Java has a nice exception handling
mechanism that enables the exception handling to be separated from the
code.

E.g you can write a clean code like

try{
// work to be done
a = getValue();
b = 1 / a;
....
}
catch(ArrayIndexOutOfBoundsException e)
{
// deal with it
}
catch(ArithmaticException e)
{
// deal with it;
}


But later I realized that this might not work all too well if I have
to give customized exception handling. For example in a snippet where
I am trying to open a file, read it with a BufferedReader and read
line by line and do stuff, most of the times the exception thrown is a
simple IOException and if I catch it in the global try catch block, I
won't know what created that exception - whether it is the reading the
file, or closing the input stream or what. So i have to go in for
little try catch blocks around each piece of code and it will be in
direct contrast to the advantage of separating the exception handling
mentioned above.


So what is the way out? In the classes that I write, I usually create
a hierarchy of exceptions like (just to give as examples)
CharacterReadingException, StreamClosingException, etc, etc which are
all derived from IOException and then I can have a global try catch
block which handles these exceptions separately and I know how they
are originated. But this certainly is an overkill and not really
flexible. Also, you cannot use it for the already existing java
classes.

Any suggestions?

Regards,
Young Seeker.
 
T

Tim Jowers

Hello everyone~

I have a question about the exception of java.

Actually, I knew how it works and how I can use it.

But what I wonder is 'when do I have to use it?'

I think that I can avoid all the situation that the exceptions occurs.

I can avoid the situation that the index of array passes the last
element or some value is divided by zero by checking the variable.

These are what I can do to prevent from zero-division as an example.

1. Avoid zero-division by check the value.
....
if(d != 0)
return a / d;
else
return -1; // Assume this return value indicates an error
simply.
....

2. Avoid zero-division by exception.
....
try{
return a / d;
}catch{ArithmeticException e){
return -1; // Assume this return value indicates an error
simply.
}
...

In java, which one is better?

If there is no exact answer for this kind of situation,
Can anyone give me guides to distinguish when to use 'code checking'
and when to use 'exception'?


Thanks for your considerations.


Java programs often use Exceptions as message passing - a real no-no
to most C++ programmers. My opinion is to write the most robust code
you can and only pass up Exceptions if you either cannot handle the
error/exception in your method or the information of the exception
should be passed up to be handled at another layer (such as displayed
in the GUI layer, handled at the layer that determines alternative
connection strategies, etc.) I'm all for creating custom Exception
types in Java when no stock ones fit the Exception.

Another big point is whether to catch Exceptions near where they occur
or just in a wide-ranging try-catch-finally. I lean toward the former
as I think it leads to more robust code; and robust code means you are
not the one stuck fixing and tracking bugs later on in the process.

Philosophically the word "Exception" is not appropriate in the way
Exceptions are used. E.g. "NumberFormatException" is probably not
anything exceptional in your code. Do you zero out or barf?

Happy Coding,
TimJowers
 
H

Harish Madhavan

Tim said:
(e-mail address removed) (zaemin) wrote in message

Exceptions will be of help if you know majority of the time 'd' is going to
be non-zero. So you could get rid of the if condition! Imagin this
particular piece of code getting executed a million times. That is, use them
for exception-al cases :)
Lets say u r implementing a socket class. In this case, chances of some
operations(read/write) going wrong is low. So an exception will be a better
alternative to return values. 'Code checking;' approach has overhead in two
ways. The client/user of this class will have to do the check everytime.
Also, the implementation willl have to populate the return value!

Also, an exception (in an API)is a better way to enforce an error check by
the client. (A return value can be ignored(or intrepreted in a wrong way),
but an exception is much more difficult to mess around with)

Another issue is with designing functions with return value. In the
scenario, x calls y calls z. The return value of x should relfect all the
possible return values of y an z. That means assigning an error code for all
the possible comibnation. But the design process will be more simpler/faster
if we say, "x will throw all the exceptions in y and z and may be more".

And I think "catch(CommunicationError e)" is more readable than "if(ret ==
COMM_ERROR)" :)

From what I've seen so far, there are soo many palces where you can use
exceptions, and is a better/cleaner way than 'code checking' Google it and
u'll find a lots of articles on this. Also, any good book on java will have
a good chapter on this ;)
Java programs often use Exceptions as message passing - a real no-no
to most C++ programmers. My opinion is to write the most robust code
you can and only pass up Exceptions if you either cannot handle the
error/exception in your method or the information of the exception
should be passed up to be handled at another layer (such as displayed
in the GUI layer, handled at the layer that determines alternative
connection strategies, etc.) I'm all for creating custom Exception
types in Java when no stock ones fit the Exception.

Good point, a return value goes immediatly to the caller, but exceptions can
be used to do a mutiple stack re-winding. This makes more sense if you have
a layered design. Exceptions can be used so that a particualr layer is
always responsible for a catergory of errors. The error could happen in any
layer, but the handler is in a particular layer, making that layer as the
error handler (no worry about the return value checks!)
Another big point is whether to catch Exceptions near where they occur
or just in a wide-ranging try-catch-finally. I lean toward the former
as I think it leads to more robust code; and robust code means you are
not the one stuck fixing and tracking bugs later on in the process.

Enclosing 3 calls with a single catch block makes the code more readable
than "a catch block per call".
But I too agree that the second approach is a better code.
 
M

Michael Borgwardt

Young said:
But later I realized that this might not work all too well if I have
to give customized exception handling. For example in a snippet where
I am trying to open a file, read it with a BufferedReader and read
line by line and do stuff, most of the times the exception thrown is a
simple IOException and if I catch it in the global try catch block, I
won't know what created that exception - whether it is the reading the
file, or closing the input stream or what. So i have to go in for
little try catch blocks around each piece of code and it will be in
direct contrast to the advantage of separating the exception handling
mentioned above.

Who says the only alternatives are a "global try catch block" vs.
"little try catch blocks around each piece of code"?

Put the exception handling where it naturally belongs. But in your
case, why do you think you "won't know what created that exception"?
The stack trace of the exception tells you quite exactly. And if it's
not about debugging but about telling the user what went wrong, then
it doesn't matter where the exception occurred, only what exception it
was (file not found, can't access file, file malformed).
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top