When does an IOException usually occur and what action should be taken to resolve it correctly?

I use file input / output streams. I know that reading a nonexistent file from a program using FileInputStream will give a FileNotFoundException . Right? Therefore, I can catch this excpetion and can return null or 0 (depending on the return type of my method that performs all these reads) to Exception to pass to the caller that the file does not exist and must create it.

But I donโ€™t know when IOException usually occurs, and what kind of reason should I tell the caller that 'this' happened because of this. I donโ€™t know exactly what 'this' and "that" is here.

Someone please specify in what cases an IOException may occur and what specific action I should take in this case. Please help. Thank you

+6
source share
3 answers

What is an IOException ?

An IOException is any unexpected issue that the JVM encounters when trying to run a program. Possible problems that he may face:

  • attempt to read from a file that does not exist
  • attempt to write to a file that has an invalid name (slash or question mark in the header should do this)
  • attempt to read the next token in the file when there are no more tokens.

When an IOException is IOException , it means that everything that throws an exception (possibly a try{}-catch that reads data from a file) can IOException , for example, if the file is not found, corrupted, etc., or when the file otherwise cannot be read, or any other of the list of problems that may arise with the IO package and its extensions.

What to do when you encounter an IOException ?

When you encounter an IOException , you can register it or print an error message. If you are reading a file that does not come out of it, you can create it to avoid future exceptions. A lot depends on what you do. If you are debugging, it is always useful to use the stacktrace function.

Refer to javadoc

+5
source

You can do the following:

  • Log exception information in a log file. You can use the following method to populate exception information.

  • Try closing InputStream / OutputStream if it is not zero when IOECeption occurs while reading / writing.

  • Throw away your own with a meaningful message so that the user knows what is happening.

+1
source

Usually when the file does not exist or you do not have read / write privileges .. etc.

Of course, there may be other things, so the best thing you can do is print a message and see what caused the exception. In addition, you can see in each class which methods throw what and when, I advise you to research this, it can help you cover more cases where you may encounter this exception.

What if you have an exception? It is up to you, your program, no specific answer for this, depends on many things.

0
source

Source: https://habr.com/ru/post/956814/


All Articles