-3

please tell the advantages of user defined exception.

why people use user defined exception and invoking it through throw key word, where the action can be simply done directly in the code block. what is the necessity of creating user defined exceptions. anybody please explain.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • To indicate (to the calling method) that something *exceptional* has happened. What action is to be simply done directly in the code block? And what if there is a problem doing it? – Elliott Frisch Jul 27 '17 at 16:26
  • 1
    Always please [search first](https://www.google.com/search?q=site%3Astackoverflow.com+java#q=site:stackoverflow.com+java+when+create+custom+exception+class) before asking. This question has been asked/answered hundreds of times previously. – Hovercraft Full Of Eels Jul 27 '17 at 16:28
  • Related question on other StackExchange site: [Pros and cons of custom exceptions](https://softwareengineering.stackexchange.com/questions/246777/pros-and-cons-of-custom-exceptions) – Hovercraft Full Of Eels Jul 27 '17 at 16:38

1 Answers1

0

Why use exceptions

Exceptions are used to indicate that something wrong has happened during the execution of code.

Not always you need to handle the exception where something exceptional happened. In this case you throw the exception to the caller.

Generally is possible to use standard existing exceptions to handle most of cases.

Why use a custom exception

If you are developing a library that can be used by others you can leave the responsability to handle the exception to the user of the library.

In this case already existing exceptions sometime are not the best solution to explain what kind of exception has been thrown. So it is necessary to create a custom exception.

If you are working in a project with other people you can do the same. Create an exception explaining what happened and leave who use your functions to handle them as needed.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56