This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

we can also write if and else condition in the place of try and catch block.  RSS feed

 
Ritesh raushan
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For unchecked exception we can also write if and else condition in the place of try and catch block.
then why we always use try catch block.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ritesh raushan wrote:For unchecked exception we can also write if and else condition in the place of try and catch block.


No, we can't. If/else serves a totally different purpose and operates totally differently than try/catch.

then why we always use try catch block.


We need try/catch to be able to handle exceptions. We usually don't catch unchecked exceptions, but occasionally we do, and more frequently we catch checked exceptions.


 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think maybe OP has seen people suggesting code like this:-That is a very inefficient alternative to an if‑else, and should be avoided like the plague.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!