Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When we create custom Error and when to create Custom RuntimeException?

 
tarek helmy
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we create custom Error and when to create Custom RuntimeException?

please explained
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what do you mean by 'custom' ?? You mean just throwing a RuntimeException or error or creating your own exception classes ?

Generally, it's always better to work with exceptions that are already contained in the jdk, since this is what other developers are already used to and makes your code easier to handle.

As for errors, don't throw them. They're to be used by the JVM when something really really messed up happens, such as OutOfMemoryError, StackOverflowError or stuff like that.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sebastian Janisch wrote:Generally, it's always better to work with exceptions that are already contained in the jdk, since this is what other developers are already used to and makes your code easier to handle.

I agree with the "generally" and reject the "always" - since a sentence with "always" is almost always incorrect.

I would say, try to use an exception from the standard Java libraries, if you can find one that's applicable to your situation. Or, try to find an applicable exception from whatever other third-party library or libraries you're using in the same part of the code where you want to throw an exception. But if none of these seems to apply, do go ahead and create a custom exception class, sure. Especially if you're reporting a particular situation that the caller might want to handle differently than they handle a generic "something bad happened" exception.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic