Student Popper
Student Popper

Reputation: 103

How to make FileOutputStream.close() to throw exception myself?

In Java, FileOutputStream.close() may throw an IOException. But I never see it happens. How can I produce such an exception? I need to produce this. Thank you.

Upvotes: 0

Views: 1790

Answers (3)

Jonathan
Jonathan

Reputation: 20385

If it's important enough, write a unit test to cover the scenario.

Consider using a mocking framework like Mockito to simulate the behaviour you require without modifying your code. For example, you can get the FileOutputStream to throw a IOException by doing the following:

final FileOutputStream out = mock(FileOutputStream.class);
doThrow(new IOException()).when(out).close();

Once you have a mocked FileOutputStream, you can then pass it into the system under test, e.g.:

myComponent.writeTo(out);

The rest is up to you, for example, how should your system behave in this situation etc...

Upvotes: 3

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

Make a program that Writes a file to a USB, let it make a pause before closing the file, take out the USB and wait till the program will try to close the file.

Upvotes: 2

JonVD
JonVD

Reputation: 4268

If your aim is to test what happens when an IOException occurs:

throw new IOException("Custom Message about the exception");

This will simulate the exception being thrown so you can see what happens in your application when such a thing occurs.

Upvotes: 2

Related Questions