Re: catch (Exception e)



Hi Max,

On Tue, 2006-10-24 at 21:42 +0200, Max wrote:
> Quite often you know why a exception will probably be thrown and that it
> does not indicate a problem. I was not explaining my self clear enough.
> i was referring to some cases in beagle like this one
> (BeagleClient/Indexable.cs, Line 287 following):
> 
> 	try {
> 		File.Delete (contentUri.LocalPath);
> 	} catch (Exception ex)
> 	{ 
> 		// It might be gone already, so catch the exception.
> 	}
> 
> Imho it would be best to catch that exception like this:
> 	} catch (FileNotFoundException)
> 	{ 
> 		// It might be gone already, so catch the exception.
> 	}
> 	
> This would also avoid catching other exceptions, that indicate a
> different problem.

Indeed, this is an oft-used thing in Beagle.

Historically the reason why these exist is usually while debugging we
would add logging in the catch block to let us know that we hit this
condition, and when it came time to check it in, we simply removed the
debug statement without removing the declaration.  On top of that until
fairly recently mcs did not report these as unused variables, and so the
warnings just weren't there.

To answer your question: no, there's no reason to declare a variable if
it isn't used.

As for doing a catch-all vs. a specific exception, I would say that it'd
have to be examined on a case-by-case basis.  In the example you
provide, it's theoretically possible that someone may have been mucking
around in /tmp and done a "chmod a-w /tmp/*" and then trying to delete
that file would throw a different exception, but one that should still
be handled (and basically ignored).

What would probably be better is something like:

	try {
		File.Delete (contentUri.LocalPath);
	} catch (FileNotFoundException) {
		// It might be gone already.
	} catch (Exception e) {
		Log.Warn (e, "Unexpected exception removing tmpfile");
	}

And if instances of the Log.Warn() are called often for a certain type
of exception, we could add a catch block for it to be silently ignored.

Joe




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]