Home > Computers and Internet > A Helper method that I kind of wish didn’t exist

A Helper method that I kind of wish didn’t exist

Something which has always annoyed me about .Net are exceptions without details. For example, there’s a FileNotFoundException and most of the time that comes bubbling up from some .Net class library, it doesn’t tell you the file that it couldn’t find. For years it’s been bothering me that whoever wrote the .Net library, didn’t include the name of the file. The method looking for the file, knows the name, why isn’t it in the exception?!
I think I now know why it’s the Marshal.ThrowExceptionForHr method. The method is a wonderful helper method that somebody pounded out, mapping error codes to english messages. Great idea for a helper method. It prevents everyone having to look up all of the possible errors which could occur from their P/Invoke call to native code. The downside is that because it’s so easy to use, that it’s used for cases where if it didn’t exist, we probably would have received a much more useful error message.
Let’s imagine a world where ThrowExceptionForHr doesn’t exist. The programmer writing some file I/O class gets to the point in the code where it has received the result of a method call. The code then checks for error or success. In the event of an error, the programmer would look up all of the different error codes, and instantiate an exception which matched the error code. When instantiating the exception they probably would have put in a useful error message (ie. a message which had the file name) because it would be so easy and useful to do so.
But since ThrowExceptionForHr does exist the programmer just checks for success and lets the Marshal class throw the appropriate exception. Now ThrowExceptionForHr has no idea what the name of the file was, and therefore can’t include it in the exception message.
If only I could find somebody’s arm to twist to check for common errors, and provide usefull error messages, before passing the error code along to ThrowExceptionForHr. 
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: