0

I have create one user-defined class (say ClassA) which extends Exception, and another class (ClassB) which extends RuntimeException. Please suggest me where I should use them in my application?

Should I use ClassB (which extend RuntimeException) in if statement like if the account balance is low?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Wahid
  • 43
  • 1
  • 6
  • 1
    going through these questions may answer your question http://stackoverflow.com/questions/7962310/user-defined-exceptions-when-do-we-use-them-what-is-an-exceptional-situation http://stackoverflow.com/questions/2612073/how-can-i-handle-user-defined-exceptions-and-after-handling-them-resume-the-flow – Zohaib Nov 18 '11 at 03:44

3 Answers3

1

An example of Runtime exception would be something that is thrown by the Runtime environment, like arithmetic or index out of bounds (the most common ones). Mostly these are technical in nature.

Business logic can be handled by extending the Exception class.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
r0ast3d
  • 2,639
  • 1
  • 14
  • 18
  • Would it be good practice of creating a Separate class(ClassB which extends RuntimeException in the project and use this like below if(value==null){ throw new ClassB(Value Cannot be Null) } – Wahid Nov 18 '11 at 05:33
  • in my mind those should be caught by enabling asertions in your development and check for assertions and disable them in production, especially for null values into method arguments. Yeach you could also do something like that as you suggested, but it is a good practice to catch these in development. Hence my recommendation for assertions. – r0ast3d Nov 18 '11 at 05:37
1

The rule of thumb Joshua Bloch suggests is:

  • use checked Exceptions (extend Exception) where you expect the application can recover from the exceptional state it came into
  • use unchecked exception (extend RuntimeException) for scenarios where you don't expect possible recovery
Jan Zyka
  • 17,460
  • 16
  • 70
  • 118
  • Please suggest any real time example – Wahid Nov 18 '11 at 09:21
  • 1
    This theme is exhausted :) I would suggest to see direct sublcasses of RuntimeException in javadoc and then use a good friend google. I even googled one nice for you: http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html Cheers – Jan Zyka Nov 18 '11 at 15:45
0

Standard exceptions are checked exceptions. So you need a try / catch block. Runtime exceptions are unchecked exceptions that don't need a try / catch block. They shouldn't occur.

For your business logic like a low account balance you should probably use checked exceptions so that you have to handle them.

Udo Held
  • 12,314
  • 11
  • 67
  • 93