What are IO Exceptions (java.io.IOException) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing premature termination? What does this mean, and what can I do to fix this exception?
Java IOExceptions are Input/Output exceptions (I/O), and they occur whenever an input or output operation is failed or interpreted. For example, if you are trying to read in a file that does not exist, Java would throw an I/O exception.
When writing code that might throw an I/O exception, try writing the code in a try-catch block. You can read more about them here: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Your catch block should look something like this:
try {
//do something
}catch(FileNotFoundException ex){
System.err.print("ERROR: File containing _______ information not found:\n");
ex.printStackTrace();
System.exit(1);
}
Here you go https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html
IOException is thrown when an error occurred during an input-output operation. That can be reading/writing to a file, a stream (of any type), a network connection, connection with a queue, a database etc, pretty much anything that has to do with data transfer from your software to an external medium.
In order to fix it, you would want to see the stack trace of your exception or at least the message, to see exactly where the exception is thrown and why.
try {
methodThrowingIOException();
} catch (IOException e) {
System.out.println(e.getMessage()); //if you're using a logger, you can use that instead to print.
//e.printStackTrace(); //or print the full stack.
}
The error message that will be printed will likely show you what the issue is. If you add the error message here, I'll be able to give you more info on how to fix that specific IOException. Without that, no one can really give you a complete answer.
It is a very generic exception that a lot IO operation can cause. A best way is to read the Stack Trace. To continue the execution you can use the try-catch block to bypass the exception, but as you mention you should investigate into the cause.
To print the stack trace:
try {
// IO operation that could cause an exception
} catch (Exception ex) {
ex.printStackTrace();
}
IOException is usually a case in which the user inputs improper data into the program. This could be data types that the program can't handle or the name of a file that doesn't exist. When this happens, an exception (IOException) occurs telling the compiler that invalid input or invalid output has occurred.
Like others have said, you can use a try-catch statement to stop a premature termination.
try {
// Body of code
} catch (IOException e) {
e.printStackTrace();
}
Related
When handling errors in Java it's common to see the superclasses being the errors that are caugh, such as
Exception, IOException, SocketException, etc.
However how do you go about finding the nitty-gritty details on the exception? How do you single a certain exception type out from the others. For instance, I'm currently working on a small project using Netty.io which throws an IOException for every type of read/write error you can name. This makes sense, because ultimately this is input/output errors, but how would I handle them individually.
Example exceptions:
java.io.IOException: An existing connection was forcibly closed by the remote host
java.io.IOException: Connection reset by peer
java.io.IOException: Stream closed
The list just continues to go on, but how would you go about handling these seperately, one approach that I've found while looking around and seems really nasty is the following.
try {
// ...
} catch (IOException e) {
if(e.getMessage().contains("An existing connection was forcibly closed by the remote host")) {
// Handle error
} else //...
}
This seems very tedious and there's bound to be a better way to do this, a correct way if you will. I've looked through quite a bit of error handling writeups over the last few hours and they all only talk about the big boys that are used commonly. IOException, Exception, SocketException, NullPointerException, and FileNotFoundException. Where I believe SocketException and FileNotFoundException would be directly related to the IOException, more than likely a subclass, correct me if I'm wrong.
Anyway, what's the proper way to go about handling these exceptions and how do you figure out exactly what kind of exception you need to be handling? All I can really do is handle IOException until something more precise comes up, but when developing applications it's always good to be able to handle each error uniquely.
In most of these cases the message is irrelevant from the point of view of your code. It's just something to be shown to the user, or logged. The only salient fact is that the connection is broken, for whatever reason, and there aren't different code paths you can use depending on which message it was.
The only one that's different is 'socket closed', which indicates a coding bug.
EDIT Regarding your comments below:
Any IOException other than SocketTimeoutException on a socket is fatal to the connection.
Invalid packets don't cause IOException: that's an application-layer problem that throws application-layer exceptions, or subclasses of IOException: e.g., java.io.StreamCorruptedException.
There is no such thing as IOException: connection closed by remote host. If the peer closes the connection, that causes an end-of-stream condition, which manifests itself as either read() returning -1, readLine() returning null, or readXXX() throwing EOFException for any other X.
I would suggest catching the exceptions in order, from most specific to least - such that you will notice a circuit break pattern when the exception you are looking for is reached. This is the best I can come up with:
try {
/// Something that can result in IOException or a SocketException
catch (IOException e){
//Do something specific
}catch (SocketExcpetion e){
}catch (Exception e) { //or some superclass of the above exceptions
///
}
Don't forget that you can also catch multiple exceptions of different types using the | command: catch (IOException|SocketException|
The documentation (http://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) contains a long list of direct subclasses. You might want to look through them and check which ones you want to treat differently.
Once you know that, you can use multiple catch-blocks, first the subclasses, then the most general IOException:
catch(SSLException se) {
// do something
}
catch(HttpRetryException he) {
// do something else
}
catch(IOException ioe) {
// nop
}
writing a system in netbeans rcp - not sure if this matters, i just don't trust the rcp
We're approaching crunch time on our system and the following error keeps happening (sometimes it happens after 10 minutes, sometimes it runs for 2 days and then happens which is leading me to believe it could be a threading error)
we have a socket reader class which implements runnable - here is a sample of the code
#Override
public void run() {
while (!Thread.interrupted()) {
try {
/*
* can't display actual code
* reads data through socket and passes stream to a new handler class
* which uses reflection to create new object based off socket stream
* (none of this happens in a separate thread)
* (we're not holding a reference to the handler class - a new one is
* -created every iteration)
*
* at some point during the creation of this object, we get a socket
* closed exception happening at SocketInputStream.socketRead()
*/
} catch (Exception ex) {
cleanup();
}
}
}
what i expect to happen is that the socket exception should just be caught by the catch block and the cleanup executed
what ends up happening instead is i get a visible stack trace (pops up in the netbeans uncaught exception window and displays in the console) for java.net.SocketException socket closed - i cannot post the stack trace due to customer requirements
what else is strange is that in the actual socket input handler class we have the following method (this is the method that the exception is actually being thrown from)
public Abstract________ new________(Class<? extends Abstract________> clazz,
DataInput input) {
...
try {
// reflection code here
} catch (Exception ex) {
LOG.error("...");
throw new RuntimeException(ex);
}
...
}
if i try manually throwing the java.net.SocketException after the catch block the exception reads java.lang.RuntimeException: java.net.SocketException exception: socket closed
yet the stack trace that we receive randomly simply says java.net.SocketException: socket closed
this is leading me to believe that in our socket stream handling class it's not even catching the exception to begin with.
Does anybody have any input as to why this may be happening???
also - i am very sorry that i can't post the actual code, i'm not trying to be cryptic
so far the one thing i'm wondering about - i am somewhat familiar with reflection but not to a great extent - when i manually throw an exception it always gets caught by the try catch block - if an exception is thrown from something in reflection is there any way it could break the try catch contract - i don't see why it would but i mean, i'm honestly not sure and grasping for straws at this point
i have received permission to post an edited stack trace
in the MessageReader class there is no separate thread - the newMessage method is where the exception is being caught, wrapped into a RuntimeException and thrown up - the ____Reader is the socket reader with the while loop
both methods do show up in the stack trace
not sure if this will help
A thrown Error (java.lang.Error) may be bypassing your catch block (which is only catching Exceptions). Try catching Error and print out whatever debug statements you need. Don't forget to rethrow the error from the catch block.
It could also be that an Exception is being thrown in the catch block.
Two possibilities come to mind:
The exception is being caught higher up in the stack trace
or, the stack trace doesn't actually contain either of the methods you've pasted
I have a code that throws a bunch of Exceptions but each of them only contains a printStackTrace() method as shown below
} catch (SecurityException e) {
// TODO Auto-generated catch block
System.err.println(e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Is this sufficient or do I need to include additional statements like System.err.println(e)? Usually, if an exception occurs I am able to trace the source with the above alone.
If there is something you can do to solve the problem, do it in the catch, if there is nothing you can do, then it is better to use a logging framework to register the exception than to use e.printStackTrace(); or System.err.println(e);
I personally recommend: http://www.slf4j.org/, but if you have masochistic tendencies you can try the very bad (but official) Java Logging API: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/ .
One extra advantage of SLF4J is that it can redirect its logging to the awful Java Logging API (that way you can use an elegantly designed API and still comform to the awfully designed (de jure not de facto) "standard"
SLF4J is easy to use, to log an exception all you have to do is write logger.error("some accompanying message", exception);, another of its advantages is that you can, for example, configure it to send you an email each time your application crashes (by using logback as the underlying logging engine)
It depends on the exceptions. Obviously, with printStackTrace() the exception will be printed for you to debug (or users to report to you). However there is no additional error handling.
Example:
If an IOException is thrown, you might want to show the user a error message specifying the exact error cause, or you might want to do another attempt, transparent for the user. Or you might want to abort the whole program if the operation is critical for the success of the whole task... etc.
If you want to trace the source e.printStackTrace() is enough.
Usually I put e.printStackTrace(); at DEBUG level. Also I add meaningful error message at ERROR level for the users.
I think you might be missing a bit about the basics of exceptions and exception handling.
The golden rule of exceptions is that they should be exceptional.
This is why you might have seen or read that you should never catch the base Exception - there is simply no way that your code can handle every time of exception.
So as a general rule you should only catch exceptions if you can handle them in a specific way. For example, if you're reading a user's details from a file and that fails you might choose to return a new user. What you don't want to do is simply catch the exception and log it. This leads to an application that is robust but simply swallows errors which leads to an extremely bad user experience.
If your method can't handle an exception it should simply not catch it and defer the exception handling to a higher level. This usually means an error message will be displayed to the user (at the top level).
If you can afford to use a logging framework like log4j, you'll be able to call
}catch(Exception e){ log.error("Exception occurred:",e}
making the log framework to log your custom message "Exception occurred" followed by the stack trace in your errorlog file
Is it a bad idea to use printStackTrace() in Android Exceptions like this?
} catch (Exception e) {
e.printStackTrace();
}
I believe this is what you need:
catch (Exception e) {
Log.e(TAG,Log.getStackTraceString(e));
}
Yes, it is a bad idea. You should instead use Android's built-in log class specifically designed for these purposes: http://developer.android.com/reference/android/util/Log.html
It gives you options to log debug messages, warnings, errors etc.
Logging errors with:
Log.e(TAG, "message", e) where the message can be an explanation of what was being attempted when the exception was thrown
or simply Log.e(TAG, e) if you do not wish to provide any message for context
You can then click on the log console at the bottom while running your code and easily search it using the TAG or log message type as a filter
Yes. printStackTrace() is convenient but discouraged, especially on Android where it is visible through logcat but gets logged at an unspecified level and without a proper message. Instead, the proper way to log an exception is...
Log.e(TAG, "Explanation of what was being attempted", e);
Note that the exception is used as a third parameter, not appended to the message parameter. Log handles the details for you – printing your message (which gives the context of what you were trying to do in your code) and the Exception's message, as well as its stack trace.
The question is: is useful at all print to the stack trace in an Andriod application context?
Will the standard output be visible at runtime? Will somebody care about it?
My point is that, if nobody is going to check the standard output and care to debug the error, the call to this method is dead code, and composing the stacktrace message is a worthless expense. If you need it only for debugging at development, you could set an accesible global constant, and check it at runtime:
} catch (Exception e) {
if(com.foo.MyEnvironmentConstants.isDebugging()) {
e.printStackTrace();
} //else do noting
}
I would avoid using printStackTrace(), use a logging system and its support of exceptions.
log.log(Level.SEVERE, "Uncaught exception", e);
So if you want to change how logging is handled it's much easier.
I've see this sort of thing in Java code quite often...
try
{
fileStream.close();
}
catch (IOException ioe)
{
/* Ignore. We do not care. */
}
Is this reasonable, or cavalier?
When would I care that closing a file failed? What are the implications of ignoring this exception?
I would at the very least log the exception.
I've seen it happen occasionally, if the attempt to close the file fails due to it not being able to flush the data. If you just swallow the exception, then you've lost data without realizing it.
Ideally, you should probably swallow the exception if you're already in the context of another exception (i.e. you're in a finally block, but due to another exception rather than having completed the try block) but throw it if your operation is otherwise successful. Unfortunately that's somewhat ugly to sort out :(
But yes, you should at least log it.
You would care if the close() method flushes written content from a buffer to the filesystem, and that fails. e.g. if the file you're writing to is on a remote filesystem that has become unavailable.
Note that the above re. flushing applies to any output stream, not just files.
The most common close() problems are out-of-disk space or, as Brian mentioned, a remote stream that's gone poof.
NOTE:
You should really see something like (note: I haven't compile-checked this)
SomeKindOfStream stream = null;
Throwable pending = null;
try {
stream = ...;
// do stuff with stream
} catch (ThreadDeath t) {
// always re-throw thread death immediately
throw t;
} catch (Throwable t) {
// keep track of any exception - we don't want an exception on
// close() to hide the exceptions we care about!
pending = t;
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e) {
if (pending == null)
pending = e;
}
}
if (pending != null) {
// possibly log - might log in a caller
throw new SomeWrapperException(pending);
// where SomeWrapperException is unchecked or declared thrown
}
}
Why all this?
Keep in mind that Java can only track one "pending" exception at a time. If the body of the main try block throws an exception, and the close() in the finally throws an exception, the only thing you'll know about is the close().
The above structure does the following:
Keep track of any throwable thrown in the body of the try
In case that exception is thread death, rethrow it immediately!
When closing, if we don't have a pending exception, track the close exception; otherwise the previously-thrown exception should be kept track of. (You should probably try to log the close() error in this case)
At the end, if there is a pending exception, deal with it. I usually wrap it and rethrow it. Personally, I use an unchecked wrapper so I don't need to have all callers in the call chain declare throws.
To do the above, I usually use the template method pattern to create the exception management and then override a doWork() method that is the body of the try.