• Post Reply Bookmark Topic Watch Topic
  • New Topic

Explanation  RSS feed

 
vishal mishra
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why "return" keyword is used inside "catch" block ?

Please Explain me !!
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think what would happen if the return statement wasn't there. What does the rest of the method do ?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because they want to exit the method at that point, and not carry out the code from lines 17 onwards?

(It's not a particularly neat way of doing it, but the intent is clear)
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseAMeaningfulSubjectLine. "Explanation" is not much clearer than "Help" - neither says anything about the issue.
 
vishal mishra
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for the subject .

About this program-:

This program is trying to read a file whose name is provided at command line.

And if the file is not found a FileNotFoundException is thrown.

I have undersood this much only.

What I am not getting is if once the exception has caught execution terminates and message is displayed given inside println keyword.

Then What the keyword "return" is doing there.

I know , I am wrong somwhere or I've misunderstood the concept, but where am i getting wrong ?

Please help me in geeting right concept.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When an exception is thrown and caught, execution doesn't terminate. It just transfers to the catch block. Unless you do something in there to stop it (like rethrowing the exception or having a return statement) execution will then continue after the try/catch block. Without the return statement this program would go on to try and read from the file it just failed to find.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Normally you wouldn't return from inside a catch block. They probably just did it here to keep this small demo program short and simple.

In a real program, if you catch an exception, you usually need to either actually handle it (such as retrying, or using a valid default value), or else rethrow it (usually wrapped in a more layer-appropriate exception. Otherwise, the caller doesn't know something went wrong. He thinks the method succeeded and everything is fine, so he goes on as if that's the case. We usually don't want that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!