tags:

views:

80

answers:

2

Is there any way to programatically differentiate between what caused an IOException? For example java will throw an IOException, if there was an error during writing. How can i tell, if its something like access violation, if the Disk is out of free space, if someone disconnected the the network drive, or other things.

I can't really parse the Message since, there does not seem to be any standardized message format, Sun (or oracle now i guess) doesn't seem to have any sort of standardized format.

Any suggestions (I am pretty new to Java, its not my normal language, but i need to use it to fix a very broken system at work.)

+2  A: 

Unfortunately Java has no equivalent of .NET's System.Runtime.InteropServices.Marshal.GetHRForException(). You tell what kind of I/O error it was only if the exception is an instance of a subclass, e.g. FileNotFoundException.

finnw
It may not be what i wanted to hear =( but you did answer me.
UberJumper
A: 

Getting a hold of the exception's exact class will give you one of a handful of possible subclasses of IOException, and these are quite standardized. You can either test classes with instanceof or (a brutish approach) compare strings returned from getClass().getName().

There are some workarounds for the other stuff; you can do a File.canWrite() on a file you're about to open for writing (well, your program should have done that anyway, if the name and/or directory can vary), and if there's a chance you ran out of file space, you could try writing a small file to a known good location and seeing if that explodes on you. Not very elegant, I know: Java is not really known as a systems programming language.

On the other hand, very often knowing a detailed cause for an exception doesn't help much: With or without the knowledge, your user may simply not be able to get the program to do what's needed.

Carl Smotricz
A possible addendum to your first paragraph - usually you're `catch`-ing these exceptions, so a nicer alternative is to have separate catch blocks for `FileNotFoundException`, `UnknownHostException`, etc. It avoids "explicit" testing and lets you handle the special cases in different blocks from the start (without precluding a catch-all `catch (IOException e)` block at the end).
Andrzej Doyle
@Ahdrzej: You're very right. I was thinking of band-aid fixes to pre-existing coding and assuming uberjumper didn't want to re-arrange the existing catch hierarchies (whatever there may be). But if "doing it right" is an option, then your way would be it.
Carl Smotricz