Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception handling

 
aditya kumar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I throw an exception without declaring it in a 'throws' clause?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Throw an exception that extends RuntimeException
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you really sure you wnat to throw an unchecked exception?

Would an Error be better?

I have to admit to feeling exceptions are used rather to much in Java, that sometimes what is an Exception actual should be an Error cos there is no way to recover from it. But I do not agree with C# method of no checked exceptions.

Check out the Java Tutorial on Exceptions, heres a discussion of Unchecked Exceptions, from the Exception tutorial.

Gavin
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gavin Tranter:
Are you really sure you wnat to throw an unchecked exception?

Would an Error be better?


Throwing Errors is very rarely a good idea, and certainly not something for beginners to do.

The idea of the distinction between RuntimeException and Error is that the former is evidence of a bug in a specific piece of code, whereas an Error is evidence of a JVM-wide problem. Examples: -

NullPointerException typically means that a particular thread has encountered a bug in a particular piece of code. But it might well be possible, and sometimes appropriate, for other threads to carry on running other pieces of code.

But OutOfMemoryError means that the whole JVM has run out of memory, and is in a state where data may be inconsistent. There is no way that any useful work can be done, once this has happened, and the only valid action is to try to close down the application as gracefully as possible.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic