I have a class for threads (implements runnable). I want to be able to print text to a file inside the method “run”, but I can’t add “throws IOException” because run() is an implementation of a method in runnable.
Of course there’s no way I’ll use a gazillion “Try-Catch” in run()…
Thanks
Dealing with checked exceptions in your
run()method is tricky for the following reasons:As @kenson john says (and you observed) you can’t simply let them propagate, because
run()is not declared as throwing checked exceptions.If you catch them and rethrow them wrapped in unchecked exceptions, they are likely to go unnoticed by the
mainthread. Why? Because the exceptions are thrown on the stack of the child thread. Unless they are caught in therun()method, they will be dealt with by the thread’sUncaughtExceptionHandlerobject … which is likely to be the default handler … which writes a stacktrace toSystem.errand then discards the exception.Now you can set another
UncaughtExceptionHandlerobject for the child thread, or even set a defaultUncaughtExceptionHandlerfor the JVM. But what should the handler do? Ideally, the exception needs to be reported back to themainthread (or whatever) to take executive action. But there’s no way that the child thread, or a handler for that thread can throw an exception on the main thread’s stack. (The best you could do to get the main thread’s attention would be to set a flag or callThread.interrupt()on the main thread … and hope that it checks the flag / interrupt status periodically.)Any
IOExceptionthat is thrown while writing to an output file indicates that something serious has gone wrong; e.g. the file system is full, or the socket or pipe you were writing to is broken / closed. So simply ignoring it could be a big mistake. (For instance, suppose that the file is precious, and that the last thing that the application does is to delete the old version of the file and replace it with the new version we just created. Ooops! We didn’t notice that the FS filled up, the new version of the file is corrupt and we just deleted the old version.)In the light of this, the
PrintStreamapproach is simplest. APrintStreamwill quietly catch anyIOExceptionthat occurs while writing, but record the fact that an exception has occurred. So when themainthread decides that everything should have finished writing, it needs to callPrintStream.checkError()to test if any errors have occurred. (Unfortunately, the API does not allow you to find out what the actual exception was.)