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?
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.
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.
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.
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.
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.
It is useful to create a custom exception if:
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.
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