Hacker News new | ask | show | jobs
by jond3k 5261 days ago
There's a problem with box 2. If the IOException is thrown in the stream's constructor (FileNotFoundException) then there will be a NullPointerException if we try to call close!

  InputStream in = null;
  try
  {
      in = new FileInputStream(new File("test.txt"));
      //do stuff with in
  }
  catch(IOException ie)
  {
      //SOPs
  }
  finally
  {
      try
      {
          if(in != null)
          {
              in.close();
          }
      }
      catch(IOException ioe)
      {
          //can't do anything about it
      }
  }
This merely proves your point! :-)
1 comments

Thanks, I didn't realize it's this bad. My only touch base with Java has been through Clojure.

This is just horrible. What braindead system forces you to check exceptions on closing a file handle? If everything failed silently and just produced 'null', the code would look like:

  InputStream in = new FileInputStream(new File("test.txt"));
  if (in) {
    ...dostuff...
    in.close();
  }
Now, that you can grasp with one glance. I'll trade the ability to write something like that with having to use malloc()/free() any day.
Silent failure doesn't carry information about how the thing failed: did the file not exist, was it not accessible because of security, was there a failure on the underlying device or file system?

How is the user supposed to figure out what went wrong with the program if the program can't even convey to the user what went wrong?

Complex problems have lots of simple wrong answers.

(Your "solution" also suggests nothing about how "in.close()" is going to get called if "...dostuff..." itself throws an exception.)