Can anyone tell me the ultimate use of user defined exception. We usually add some messages to that exception object and throw to web layer either from business layer or DAO layer. Anything else. Thanks in advance..
It allows you to catch all user-defined Exceptions with one catch, of so required, whilst ignoring built-in Java™ Exceptions. You create one Exception class and make all your Exceptions subclasses of that. Then you can catch as few or as many of those as you wish, without interfering with handling of any other kinds of Exception.
Thanks for the reply. I have some doubts on your statement. Please correct me, if I understood your explanation wrongly. If we are getting some exception in a particular peice of code, we need catch all those one by one like arithmaticexception, sqlexception and finally exception in catch block... we can avoid this by creating the user defined exception, we can ignore the order of exception in catch block...? please give me one example to understand your statement. Thanks in advance.
User defined exception is not to avoid having multiple blocks of exception. It is to define your own exceptions that ensures you handle application specific exception like a banking application with savings bank account that ensures the user cannot withdraw more than the account balance, you might want to define NotEnoughFundsException
. . . you might also define a BankException and make the NotEnoughFundsException extend it. You can have a complete hierarchy of Exceptions and catch as many or as few types as you like. You can catch them all with
The above NotEnoughFundException and BankException makes more comfortable. For example if user tries to with draw extra amount than the available,we ill throw some exception to notify the user. We will do that by calculating the data base value purely. Cant we use exception class alone to do this job. What is hidden requirements in creating the user defined exception here. Anyway based on the calculation we can throw exception with message that Not enough fund. Please advice me further.
It would be better design to send a query before a withdrawalIf you didn't have your NotEnoughFundsException, what sort of Exception would you use? Another thing is I have enhanced your Exception by allowing you to add the amount and the account number to its constructor as fields.