Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can we do with custom exception?

Tags:

c#

.net

exception

I don't know what we can do with a custom exception, what we can't do with a built-in one. It seems a naive question but I really have no idea about that. What do you think?

like image 927
Nam G VU Avatar asked Sep 21 '10 11:09

Nam G VU


People also ask

What is the use of custom exception?

In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword. For example, MyException in the below code extends the Exception class.

Why would I use a custom exception class?

The purpose of a custom exception class is to integrate the look-up of localized message strings in a custom message catalog into the mechanism that is used for error reporting in the client infrastructure.

Can we throw custom exception?

As you can see, all you need to do to throw your custom exception is (1) create a new instance of the exception (new AlsCustomException("Anything but zero ...")), and then (2) throw that exception with the throw keyword.

What is an exception used for?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.


2 Answers

The reason for the different types of exceptions is to allow you to be able to catch just the ones you want with your handlers, letting the others go on up the stack. So you can arrange to catch exceptions for certain, occasionally-expected situations just by the type of the exception.

You may not need to create your own very often at all, actually. But if you do, it would be because you need to be able to throw and capture an exception type more specific than what is available, and perhaps with additional information attached.

like image 173
Andrew Barber Avatar answered Oct 23 '22 21:10

Andrew Barber


It is useful to create a custom exception if:

  • There is no built-in exception that expresses the type of error condition you have.
  • You want to catch only that specific type of exception and not exceptions coming from the framework.

But usually if there already is an exception in the framework that you could use then it is better to use it instead of creating your own exception for the same thing.

like image 34
Mark Byers Avatar answered Oct 23 '22 23:10

Mark Byers