Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET

Exception Handling - Not Just a Good Idea

5.00/5 (1 vote)
20 Dec 2011CPOL2 min read 19K  
You have everything you need to do your job as a developer. You just need to use them.

So there I was, converting a group of legacy ASP web pages into a single ASP.Net web page. This web page presented several files for the user to download, and depending on the query string, the files' extensions change. One of the extensions is .TXT, and in this case, I had need to display slightly different text depending on whether or not the file's size was 0 (for the other two extensions that are supported, if the file is there, it's always greater than 0 length). For the .TXT files, I was using Server.MapPath to get the file's physical path on the server, and the FileInfo object to determine the file's size.


Coding was relatively uneventful, but when I started testing the TXT file variant of the page, I was getting a rather cryptic error message when the page tried to render:



The application has encountered an error.



After about 20 minutes of chasing Server.MapPath around, I narrowed the problem down to the use of the FileInfo object.

I could create a FileInfo object, but when I tried to use the Length property, I would get the error message cited above. In a last ditch effort to find out why this was happening, I put a try/catch block around the code in question, and was IMMEDIATELY notified that the file couldn't be found. This led to the 2nd realization that the page was in a different location, so NONE of the files were where I assumed they'd be, which in turn led to changes to a DTS package and a utility on another server.

My first reaction was to wonder why the object's constructor didn't throw an exception if the file couldn't be found, and I suppose the answer to that lies deep within the belly of the Redmond beast that spawned the evil that is .Net. On the other hand, it led me to share this tip:


Use all of the tools at your disposal.
Your job will honestly become that much easier.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)