Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use try/catch and throw ?

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

When to use try/catch with no throw block and when to use throw.I mean when we use the throw statement.
 
Siddhesh Deodhar
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you want to do any "work" after exception is thrown you will definitely go for using "Try/Catch" block.
Suppose your method does not bother with what operation it is doing and exceptions may come there then you will go for "Throws" block which says
this method may throws exceptions. As simple as that.
Its always good idea to use Throws and get all exceptions at outermost point(Usually in web applications).
 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
could you please give me both case example its better to understand
 
Siddhesh Deodhar
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose you have a function which reads a simple text file and prints its content. In this case this function should have a try catch block within which you will
read a file and print its content. So here if any exception comes while reading a file you will have to handle proper message to be displayed to the user in catch block.
Suppose you have a function which will return content of file as a String to its caller than it will be like follows

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the below Code could you please tell me how the flow of Exception will work and why ?

 
Ilari Moilanen
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you call throwdemo() inside your main it will throw IllegalStateException on line 7 and it will be caught on line 22. It will not be caught on line 9 since IllegalStateException is not NullPointerException.

Since IllegalStateException is a subclass of RuntimeException you do not need to declare "throws" on line 3 as you normally would. But since it is a exception that is not caught it will still propagate up to the calling method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic