Programmatically determining the cause of IOException?
Is there any way to programmatically 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 it's 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 standa开发者_如何学Pythonrdized format.
(I need to use Java to fix a very broken system at work.)
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
.
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.
精彩评论