Forums Register Login

Need help with Exceptions

+Pie Number of slices to send: Send
I am having problems with the try/catch of IOException and Exception



public void generateReport()
{


try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outputFile.text")));
} catch (IOException ioe) {
System.out.println("Can't load the file: " + ioe);
ioe.printStackTrace();
throw ioe;
} catch (Exception e) {
System.out.println("Problem: " + e);
e.printStackTrace();
throw e;
}

}

compiler says it is an unreported exception and must be caught or declared to be thrown. I don't understand what this means. Please help
+Pie Number of slices to send: Send
Hi April,

Welcome to JavaRanch!

In both catch blocks, you report the error, and then re-throw the exception. Those exceptions will "escape" the current method, since they're not re-caught anywhere here; thus, as you've written it, the method itself needs to say something like

public void generateReport() throws IOException, Exception {

But I don't think you should write it this way. You should think a little about how to handle exceptions in a good way. If you want someone who calls generateReport() to get an IOException if the operation failed, then generateReport() should, indeed, say "throws IOException" at the top, and your generateReport() method shouldn't bother printing a message or even catching the exception and rethrowing it -- just let it escape.*

On the other hand, catching generic Exception is a bad idea almost always. This will for the most part catch exceptions that come from programming errors, and you really don't want to waste your time writing code to deal with errors you've made in writing your code. Just drop the "catch (Exception)" block altogether.

-----------------------------
Footnotes:
-----------------------------

* But if it escapes, the file will stay open, so you should consider using a try... finally block to make sure the file gets closed even if there's an error.
+Pie Number of slices to send: Send
Thank you, but what is a try... finally block
+Pie Number of slices to send: Send
Take a look at chapter 80 of Bradley Kjell's Introduction to Computer Science using Java.

You might also like to read the Catching and Handling Exceptions lesson of Sun's Java Tutorial.
[ September 23, 2004: Message edited by: Dirk Schreckmann ]
When evil is afoot and you don't have any arms you gotta be hip and do the legwork, but always kick some ... tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 587 times.
Similar Threads
which catch start first ?
Exception
Invalid Stream Header (?) - Please help
try/catch
Chained Exceptions, Am I doing it correct?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:01:56.