Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with Exceptions  RSS feed

 
April Benzine
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
April Benzine
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, but what is a try... finally block
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!