Java: Exception Handling Practices

Status
Not open for further replies.

Timothy Mark

Ars Tribunus Militum
2,824
Subscriptor++
It Depends(tm).

If this is just a class assignment, you generally do something like this:
code:<HR>
Code:
try {
   // do stuff
} catch(Exception e) {
   System.out.println("your fucked");
   System.out.println(e.getMessage());
   System.exit();
}

You indicated in your other thread that you're new to java, so I wouldn't worry about much more than that for now.
 

Young Mr. Grace

Smack-Fu Master, in training
97
I group exceptions into 3 types: fatal ones like minordeity posted, ones I can handle by throwing to the calling function, and my own message passing exceptions that I use to in place of good programing practices. Basicly, if I'm expecting several things to happen in a function but case 1 is more likely than the rest, I'll just have the function handle case 1 normally, then everything else will be my own exception instance. I like doing this because it kind of segregates the code in to little functional blocks and I don't end up with big long blocks of code that handle every concievable case.
 

newton_meter

Ars Scholae Palatinae
1,424
Originally posted by MinorDeity:
It Depends(tm).

Yeah, it does. It depends on lots of things. Here are some suggestions, all of which can be broken whenever you feel like it.

1. How likely is the exception? Sometimes, you can't know. Sometimes, you can. If it's once per run of the program (e.g. a EOFException used algorithmically to detect the end of a file) then you may handle it differently than if it's a lightning strike kind of event.

2. Can I recover from the exception? Is there a way to recover from the exception? You might be able to recover automatically, or perhaps with user assistance. Or, maybe you're SOL (e.g. the OS failed to create a TCP socket for you).

3. Handle the exception or ignore? Are you going to do something to handle the exception, or will you just ignore it (possibly logging it to the console or a file)? This may depend on the answers to 1. and 2. above.

4. Where? I tend to catch exceptions that I'm handling near where they occurred. If I'm going to ignore them, I tend to widen the scope of the try to include as many such exceptions as possible. But not always.

5. How do multiple exceptions interact? If you've got a try block where N possible exceptions may be thrown, is it important to know which exception (and where it) occurred? Will you recover from the exceptions differently, or will you handle them all in the same way?

6. Exceptions are a control structure. How do they interact with other control structures? Be aware that an exception can cause you to jump (or not) out of a loop, or a conditional, or a switch. Do you want to (or not)?

I often stick an empty catch in when I'm initially building something, but I'll usually add a special string in a comment that I can search for when I want to make sure I've actually handled everthing.

Here's an example of bad exception handling that is fresh in my mind. It was a careless bit of code that required an unfortunate amount of time to track down and fix.

This is the main dispatch loop of a thread that is receiving messages on a TCP socket. The intent is to repeatedly read a message on the socket's input stream and process it:

code:<HR>
Code:
while (true) {
  try {
    int messageType = in.readShort();<P>    ...
  } catch (IOException e) {
    e.printStackTrace(errLog);
  }
}

There's a huge block of code where the dots (...) are. If any of it throws an exception, the developer didn't know what to do, so he just decided to print a message to a log file.

The attempt to read a short on the socket blocks until two bytes are available. An attempt to read from a socket which is no longer connected results in an IOException (EOFException, subclass of IOException). When the client (on the other end of the socket) closes the socket, the readShort throws the exception. The exception is caught, logged to the error file, and the loop is reentered. Repeat. OMG, a blocking read just turned into an unintended spin wait! It happens on a "server"; it caused performance to degrade drastically and required a human to have to go find the java processes and kill them. Oh yeah, and huge error log files. Yucky.

One easy solution would have been to widen the scope of the try so that it encloses the while. Then, an IOException would jump out of the loop. This may or may not be desirable. A better solution is to catch EOFException and handle it (by jumping out of the loop), or to inquire of the socket if it's still connected in the IOException handler.

(kg*m*m)/(s*s)

[I just read Midlands post to your other thread. I would echo his suggestions.]
 

Nimdok

Ars Scholae Palatinae
1,214
When I first began dealing with exceptions, I became very frustrated because I felt obligated to handle them all as they came along. So my advice is:

Don't be afraid to throw exceptions.

code:<HR>
Code:
public void parseData(byte[] data) throws IOException {
}

If you have a set of classes that are responsible for reading from a file, set it up so they all throw IOException. Then you can catch the error cleanly at the top class, and deal with it in one place.

Also, avoid catching exceptions and blindly moving on:

code:<HR>
Code:
try {
	//spawn a new thread, make socket connection, etc.
}
catch(Exception e) {
}

Hey, something really wrong could have happened there. Your thread might not have spawned. You might not have made the socket connection. There's a reason those methods are throwing exceptions! :) Don't catch and move on, throw.
 

Midlands

Ars Praetorian
535
Subscriptor
I agree about not being afraid to throw exceptions.

I find that most exceptions bubble up to a 'natural level'. That is, there's usually some level of code at which it makes sense to deal with them -- just realize that that level may be quite a few frames up the stack.

For example, if you have a program that synchronizes a local directory with a web site, you will have low-level machinery that reads and writes files. The top level -- where you do the synchronization -- may be quite a few function calls away, and, yet, each one of them will throw IOException. There's nothing wrong with that.

Exceptions are very powerful; use their features. In particular, having a stack trace is a truly killer feature from Java -- it's incredibly useful when debugging. If you're using printf debugging (erm, 'System.err.println' debugging), it can be useful as a trick to just say "new Exception().printStackTrace();" (yes, you can do that) to show how you got to a particular bit of code.

Also, keep your exceptions well-informed. Don't just "throw new IOException()" or even "throw new IOException("Can't read file")"; do a "throw new Exception("File '" + fileName + "' not found.")". This will make debugging *much* easier.


Oh, yeah. I tend to follow the rule that says 'use exceptions only when truly exceptional conditions occur'. This is a matter of judgement, but it does say that if you *expect* exceptions to get thrown from code, you're using them as a control structure rather than an error-handling mechanism, and you might want to think about refactoring your code. This is not always bad -- but, as a beginner, I'd tend to think about them in terms of error handling. They're a non-local 'goto', otherwise, and provide enough craziness to really confuse yourself otherwise.
 
Status
Not open for further replies.