I am using File Input/Output streams. I know that reading a non-existent file from program using FileInputStream
will give FileNotFoundException
. Right? So I can catch this excpetion and can return null or 0 value(depends on return type of my method performing all this reading operations) on Exception to convey the calling program that file does not exist and should create the one.
But I don't know when IOException
generally occurs and what is the exact reason I should convey to calling program that 'this' has happened because of 'that'.
I exactly don't know what is 'this' and 'that' here.
Anybody please elaborate me in what cases does the IOException
can occur and what specific action should I take in such case.
Please help. Thanks.
There are two ways to handle the IOException in java: By using good programming while writing the code. Using the try and catch, is one of the most useful methods to avoid any kind of exceptions whether it is checked or unchecked.
It can throw an IOException when the either the stream itself is corrupted or some error occurred during reading the data i.e. Security Exceptions, Permission Denied etc and/or a set of Exceptions which are derived from IOEXception .
IOException is the base class for exceptions thrown while accessing information using streams, files and directories. The Base Class Library includes the following types, each of which is a derived class of IOException : DirectoryNotFoundException. EndOfStreamException. FileNotFoundException.
If both base and derived classes are caught as exceptions, then the catch block of the derived class must appear before the base class.
What is an IOException
An IOException
is any unexpected problem the JVM encounters while attempting to run a program. Possible problems that it may encounter are:
When an IOException
is thrown, it means that whatever is throwing the exception (perhaps a try{}-catch
block that reads data from a file) can throw an IOException
, for example if the file is not found, corrupted, etc, or when the file is otherwise unable to be read, or any other of a list of issues that can occur with the IO
package and it's extensions.
What to do when you encounter an IOException
?
When you encounter the IOException
, you could log it or print an error message. If you are reading from a file that does not exit, you could create one to avoid future exceptions. A lot depends on what you are doing. If you are debugging, printing the stacktrace is always helpful.
Refer to the javadoc
You can do the following things:
Log the Exception information on a log file. You can use the following method to populate the Exception information.
Try to close the InputStream/OutputStream if it is not null when the IOECeption happens in reading / writing.
Throw an Exception of your own with meaningful message to let user know what happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With