• Post Reply Bookmark Topic Watch Topic
  • New Topic

Catching exception  RSS feed

 
S Majumder
Ranch Hand
Posts: 349
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi every body I have a question ,
Could I catch NullPointerException or ClassCastException in the catch block ?

regards,
S
 
Somnath Mallick
Ranch Hand
Posts: 483
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you can catch NullPointerException and ClassCastException. But it certainly isn't a very good idea to do so with NullPointerException !
Read this:
https://www.securecoding.cert.org/confluence/display/java/EXC09-J.+Do+not+catch+NullPointerException

 
S Majumder
Ranch Hand
Posts: 349
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply ,
one thing I need to clarify , NullPointerException I think run time exception , so should we go for run time exception to catch it in the catch block ?
What about ClassCastException ?


regards,
S
 
Somnath Mallick
Ranch Hand
Posts: 483
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From what i know, it isn't a very good thing to catch RuntimeExceptions to avoid or just to log them, because they denote serious bugs in your code. Something which you should handle within the code. This is what i feel. Wait for some others to reply.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Somnath. 99% of all RuntimeExceptions can be prevented by checks; in case of NullPointer that is "!= null", with ClassCastException that is using "instanceof".
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should consider why you are suffering those Exceptions in the first place. Not only can they be prevented by the tests rob mentioned, but they may indicate more serious errors. Why have you got a null reference in the first place?
 
Rok Štelcer
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I guess you should read the following lesson:
http://java.sun.com/docs/books/tutorial/essential/exceptions/

In general you have two types of exceptions:
  • checked
    They represent an invalid conditions in areas outside the immediate control of the program ... so if they happen, it is not a programmer fault.
    Example of an checked exception is IOException.
  • and uncheked
    These are usually NullPointerException, IllegalArgumentException, etc. ... bottom line, all this exception will be thrown if programmer will try to do something he shouldn't.
    All these are the result of our stupidity. ;)

  • Hope this helps.


    Regards,
    Rok
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!