aspose file tools*
The moose likes Beginning Java and the fly likes When to use try/catch and throw ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to use try/catch and throw ?" Watch "When to use try/catch and throw ?" New topic
Author

When to use try/catch and throw ?

Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 391
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

Joined: Mar 05, 2009
Posts: 118
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).


Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 391
could you please give me both case example its better to understand
Siddhesh Deodhar
Ranch Hand

Joined: Mar 05, 2009
Posts: 118
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

Joined: Oct 04, 2006
Posts: 391
For the below Code could you please tell me how the flow of Exception will work and why ?

Ilari Moilanen
Ranch Hand

Joined: Apr 15, 2008
Posts: 198
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use try/catch and throw ?