Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Create Custom Exceptions? [closed]

Tags:

c#

.net

exception

Why do we need to create custom exceptions in .NET?

like image 316
Yoann. B Avatar asked Jan 06 '09 17:01

Yoann. B


People also ask

Why do we need to create custom exceptions?

Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception. These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.

What is the advantage of creating your own custom exception class?

The big advantage is that it allows you to throw and exceptions that mean what you want them to mean. If you reuse an existing exception, any piece of your code that catches the exception has to deal with possibility that the actual exception wasn't thrown by your code, but by some other library party code.

What are some of the points you should consider before creating custom exceptions?

Three steps to create and use custom exception class (1) Define exception class (2) Declare exception prone method with throws keyword (3) Check condition to throw new exception object to be handled by calling the method.


2 Answers

Specific customs exceptions allow you to segregate different error types for your catch statements. The common construct for exception handling is this:

try {} catch (Exception ex) {} 

This catches all exceptions regardless of type. However, if you have custom exceptions, you can have separate handlers for each type:

try {} catch (CustomException1 ex1) {     //handle CustomException1 type errors here } catch (CustomException2 ex2) {     //handle CustomException2 type errors here } catch (Exception ex) {     //handle all other types of exceptions here } 

Ergo, specific exceptions allow you a finer level of control over your exception handling. This benefit is shared not only by custom exceptions, but all other exception types in the .NET system libraries as well.

like image 64
Jon Limjap Avatar answered Sep 27 '22 23:09

Jon Limjap


I did a lengthy blog post on this subject recently:

http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx

The crux of it comes down to: Only create a custom exception if one of the following are true

  1. You actually expect someone to handle it.
  2. You want to log information about a particular error
like image 22
JaredPar Avatar answered Sep 27 '22 22:09

JaredPar