Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET - When to use custom exceptions?

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?

like image 998
ebb Avatar asked Sep 06 '10 19:09

ebb


2 Answers

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

  1. To convey more detailed and specific information about the error.
  2. To provide a means to catch this error conditions (i.e. 'FileNotFoundExeception', this allows a business decision to be made at a higher layer.)
like image 173
Chuck Conway Avatar answered Sep 27 '22 16:09

Chuck Conway


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?

like image 28
Wyatt Barnett Avatar answered Sep 27 '22 16:09

Wyatt Barnett