2

In Java we have the ability to write our own Exceptions.

Why would I want/need to do this? What are the upsides or advantages of doing so?

Why should I create my Exception, rather than adding to the catch of a standard Exception?

Chris Sprague
  • 740
  • 1
  • 12
  • 22
ju ho
  • 318
  • 1
  • 17
  • 1
    imagine a scenario where your system works on a specific condition like employee age must be more than 25 here it will be nice to have a exception check if user enter his date of birth which is making him underage, its a very vague example but its just an simple scenario there are complex scenarios but unfortunately cant think of any right now – Kumar Saurabh Sep 03 '15 at 12:51

3 Answers3

7

You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else’s.

  • Do you need an exception type that isn’t represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else’s exceptions, will users have access to those exceptions?
  • A similar question is, should your package be independent and self-contained?

Taken from "2. Creating custom Exception" in this article.

assylias
  • 321,522
  • 82
  • 660
  • 783
Jürgen K.
  • 3,427
  • 9
  • 30
  • 66
2

If you need to throw an exception for an unrecoverable situation (in other words, you don't plan to catch and handle it), then do not create your own exception type.

However, there are legitimate (though quite rare) cases where exceptions actually are used to signal recoverable exceptional circumstances. In those cases it is the best option to create your own exception type to represent your domain-specific circumstance.

BTW when I say "handle", I mean more than log or return a general failure response. The handling code should "live with" the exception and apply some business logic to proceed.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

You don't necessarily need to, but if you're creating for example a library, you might want to create your own exception hierarchy to go with it.

Well named custom exceptions will provide additional information, but often you'll find existing exceptions that will meet your requirements (you don't need to make your own IllegalArgumentException or similar exception types).

Kayaman
  • 72,141
  • 5
  • 83
  • 121