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

Exceptions

 
Lovleen Gupta
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whats the use of having a return statement in a catch or finally block?
Basically, how does the rpogram flow, once it encounters a return statement?
For exp, in the program below, what will be the output if "Hello.txt" doesn't exist:


Thanks..
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guptajee,


Posted By Lovleen Gupta
Whats the use of having a return statement in a catch
or finally block? Basically, how does the rpogram flow,
once it encounters a return statement?


Suppose,if exception is thrown, you want to make return statement,
and no other statement execution of the method to proceed. But finally
will execute for sure unless you write System.exit(1) or something that
terminates the program. Suppose you dont write "return -1;" in your catch
clause, even after exception comes, a line that may outside of the try catch
clause will execute and may yield undesirable result. So you wrote "return -1" there.

Got it?


Regards,
cmbhatt
 
Lovleen Gupta
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chandra Bhatt:
Hi Guptajee,



Suppose,if exception is thrown, you want to make return statement,
and no other statement execution of the method to proceed. But finally
will execute for sure unless you write System.exit(1) or something that
terminates the program. Suppose you dont write "return -1;" in your catch
clause, even after exception comes, a line that may outside of the try catch
clause will execute and may yield undesirable result. So you wrote "return -1" there.



Got it?


Regards,
cmbhatt


So, in this program, why is -1 printed and not 0?
Please explain.

Thanks.
[ April 12, 2007: Message edited by: Lovleen Gupta ]
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Gupta,

System.exit(0); //Normal termination of the program
System.exit(-1); //Supposed to be an abnormal termination of program

But as you return anything from the method, generally -1 shows that something
went wrong. You can even return 3, 13 , and 43 if you treat as it is abnormal
return from the method. (It is upto you). But general practice says negative returned value, something abnormal happened there.


Got it Guptajee?

Regards,
cmbhatt
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic