1

What can I do to make my code throw an IOException?

I have tried reading from and writing to a file that does not exist. But that throws a FileNotFoundException.

What are some specific things that throw an IOException?

Alea Kootz
  • 913
  • 4
  • 11
prashanth
  • 69
  • 7
  • Well, other any other IO problems. For example, what if the file is deleted while you're reading it? What if you try to read past the end of the stream? etc. – Andy Turner Apr 05 '17 at 19:38
  • 1
    The class names of [known subclasses of `IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) should give you some hints as to the types of things that can go wrong. – Andy Turner Apr 05 '17 at 19:39
  • EOF reading, Socket closed, access denied, ... – ControlAltDel Apr 05 '17 at 19:40
  • This question was in Triage, I've edited the problem statement to bring it in line with stackoverflow standards. Please review https://stackoverflow.com/help/how-to-ask for an understanding of the way questions should be presented. – Alea Kootz Apr 05 '17 at 20:01

1 Answers1

2

If you want to throw an IOException() deliberately, you should simply throw a new IOException() like so:

throw new IOException();

This is the correct way to deliberately throw an exception. Deliberately causing an exception to be thrown is not good practice, as it will make the exception look genuine.

Here is the full list of exception subclasses that can throw an IOException():

ChangedCharSetException, CharacterCodingException, CharConversionException,
ClosedChannelException, EOFException, FileLockInterruptionException, 
FileNotFoundException, FilerException, FileSystemException, 
HttpRetryException, IIOException, InterruptedByTimeoutException, 
InterruptedIOException, InvalidPropertiesFormatException, 
JMXProviderException, JMXServerErrorException, MalformedURLException, 
ObjectStreamException, ProtocolException, RemoteException, SaslException, 
SocketException, SSLException, SyncFailedException, UnknownHostException, 
UnknownServiceException, UnsupportedDataTypeException, 
UnsupportedEncodingException, UserPrincipalNotFoundException, 
UTFDataFormatException, ZipException

This list is from https://docs.oracle.com/javase/8/docs/api/java/io/IOException.html.

Alea Kootz
  • 913
  • 4
  • 11