Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

catch(Throwable t) ??

 
sudharshan tettu
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

What is use of catch(Thowable t) over catch(Exception ex)

I which case that one is used

Thanks
Sudharsan
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Throwable is used to catch everything which can be thrown ( i.e. Errors and Exception ).

For more information, please read the API Documentation.

Regards ...
 
Rahul Bhattacharjee
Ranch Hand
Posts: 2308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by sudarsan tettu:

What is use of catch(Thowable t) over catch(Exception ex)


catch(Exception e) : catches both runtime and checked exceptions.In ideal programs runtime exceptions are not to be caught.Excluding special conditions like in case of a B2B application where the client in expecting something which would suggest that a exceptions has taken place (like error code ), but actual exception might not be making sense for the client.So in those cases you might want to catch the exception and send error code.

Another conditions is when you want your program to continue even after a Fatal blow.In that case also catching runtime exceptions might help.


catch(Throwable t) : catched runtime , checked exceptions and errors too.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference is that catch(Exception e) is something you are supposed to do and catch(Throwable t) is something you aren't.

Not a good idea to catch a Throwable because:-
  • You might miss a ThreadDeath which ought to be re-thrown, and
  • You might be overlooking an Error which makes it impossible for your application to run properly anyway.

  • Actually catch(Exception e) is not really a good idea either; you are better off catching subclasses of Exception.
     
    Rahul Bhattacharjee
    Ranch Hand
    Posts: 2308
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Campbell Ritchie:
    You might be overlooking an Error which makes it impossible for your application to run properly anyway.

    Very correct.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic