Why do we need to create custom exceptions in .NET?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With