• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Handle Exceptions

 
Mathews P Srampikal
Ranch Hand
Posts: 211
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to handle UnCheckedException at runtime.
Thanks,
Mathews.
 
Joe Ess
Bartender
Posts: 9318
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. Typically, the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them."
The Java Tutorial
For example, one is unlikely to solve a java.lang.OutOfMemoryError by catching it and calling System.gc(). It is usually a symptom of a much larger problem, like an infinite loop allocating memory.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unchecked just means the compiler won't force you to handle a possible exception. I might be able to call someMethod() without putting it in a try/catch block, which means someMethod() does not declare any checked exceptions. But it still might throw an unchecked exception.
It's tough to know whether you should bother to catch them or not. Think about what you would do in response to, say, a null pointer exception. Could you recover, provide a default value for a parameter and try again, all with no user input? This doesn't work out very often so it's common to let them go unchecked. Then they percolate up to the calling method and so on.
But if any exception bubbles up far enough, it will terminate your program, and that's probably bad. So at some high level you want to catch Exception or even Throwable and prevent them from crashing everything.
BTW: Exception handling is an area of much controversy. Some very smart people think Java got it wrong, and they recommend using only unchecked exceptions so you never have to put "throws" on a method. I'm writing a web server now that lets all exceptions bubble up to a very high level routine that just pumps out an error message. It would be cleaner without "throws" on almost every method. Other very smart people think Java got it right and like to be very explicit about what can possibly be thrown as honest documentation. It's hard to say there is a right or wrong answer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic