Exceptions (was Re: Structs (was RE: Record selectors))

Luke Gorrie luke@REDACTED
Thu Jan 16 17:58:36 CET 2003


Richard Carlsson <richardc@REDACTED> writes:

> It looks like the only real problem here is that the file API does not
> offer a function that captures one of the most common uses (the
> traditional "just close this file if it's open, dammit") but only the
> totally generic "I'll tell you about anything that might happen during
> the operation" method file.close(). Of course, you can write that one
> yourself as a utility function, which might be a good idea in this
> example.
> 
> Apart from that, I don't think you can come up with any piece of code
> that gives you the exact (and nontrivial, if you think about what it
> does) error handling that your example contains, using fewer tests
> and/or being more concisely written. (Maybe test for file==null before
> reading starts?)

How about:

  InputStream		file = null;

  try {
      file = new FileInputStream(...);
      read from file;
  } finally {
      if (file != null)
          file.close();
  }

That should be within spitting distance of the same semantics, I
*think* the only difference is that it will never try to close() the
file twice. Well, and if an exception is trigged inside the 'try' and
also by file.close(), I'm not exactly sure which one propagates - but
"probably" you don't care.

I think this captures the intent better too: you don't want to catch
(suppress) any errors, you just want to setup the invariant that the
file will be closed.

> On Thu, 16 Jan 2003, Shawn Pearce wrote:
> 
> > 	InputStream		file = null;
> > 
> > 	try
> > 	{
> > 		file = new FileInputStream(...);
> > 		read from file
> > 		file.close();
> > 	} catch (IOException ioe)
> > 	{
> > 		if (file != null)
> > 		{
> > 			try
> > 			{
> > 				file.close();
> > 			} catch (IOException ioe2)
> > 			{
> > 				// What do i do if i can't close the
> > 				// file during an error? Assume it's
> > 				// ok to ignore the second error?
> > 			}
> > 		}
> > 
> > 		throw ioe;
> > 	}



More information about the erlang-questions mailing list