Hey there, I keep hearing over and over again that I should ALWAYS use custom exceptions in my web apps.. The problem is that I dont see any reason for making custom exceptions when they all are handled in the global.asax(write to database etc.) anyway.. So why should I use them?
I almost never use custom exceptions. When I do manually throw an exception I provide a detailed message.
I've found the maintenance of the exceptions is not worth the hassle.
Update
Lets put this into context. The Question is if someone should create custom exceptions in a web application. I envision this as a basic crud app.
Web Applications
In Web Applications you almost NEVER need custom exceptions. Data is being written to the database and data is being read from the database. The data is then consumed by some sort of UI: MVC, WPF, WebForms... etc. In such an app, there is not a opportunity for custom exceptions. Every application is different, so there will be exceptions to this...
Frameworks
Frameworks are an entirely different animal. As a framework developer it's your job to provide visibility into why an error has occurred. I expect verbose exceptions from a framework, maybe custom, maybe not. I expect enough information to solve the error.
As @Wyatt Barnett pointed out a new exception should offer something more, something that can not be done with an existing class.
Reason I Would Create a Custom Exception
- To convey more detailed and specific information about the error.
- To provide a means to catch this error conditions (i.e. 'FileNotFoundExeception', this allows a business decision to be made at a higher layer.)
Having proper exceptions class for a given exception or problem is very important for the code that will use the class you are writing.
Example, the WriteLine method of TextWriter
can throw the following exceptions:
ArgumentNullException
ObjectDisposedException
IOException
FormatException
Imagine your code if that method would throw only Exception
.
I think the line for where it becomes a good idea for making your own custom exceptions rather than just using standard sorts of exceptions with descriptive errors comes somewhere at the point where you need to add more data to the exception. EG, just imagine you had an import routine and rather than just throwing an InvalidOperationException when you get mangled data, you could throw an ImporterException and include in said exception the row number and raw data of the import?
Let's break down the use of exceptions:
We throw an exception when our routine encounters this situation:
"I cannot continue"
We throw a specific BCL exception when our routine encounters this situation:
"I cannot continue and one of the more specific BCL exception types describes the precise reason why (i.e. FileNotFoundException)"
We throw a custom exception type when our routine encounters this situation:
"I cannot continue because of a reason which none of the BCL exceptions can accurately describe to interested parties"