• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
Bartenders:
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

Error catch Q  RSS feed

 
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code, Three questions.

1. if both return statements are commented, compiler gives error saying "missing return statement" - Why compiler expect return statement ?

2. If return "Peace" statement is uncommented or both statements are uncommented, it prints "Peace"

3. If only return "Error" statement is uncommented then i gets expected error divide by zero.

 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. If you define a method as returning a String, every normal exit from the method must return a String. Just reaching the final brace is the same as having plain return; as your last statement, which violates your contract to return a String.

2,3. After dividing by zero, you will always leave the catch clause abnormally without reaching the [return " error ";] statement. The question is what happens then. If the finally clause is empty, the program will terminate with a stack trace printed unless there is a higher enclosing try/catch statement. If you transfer control with a return statement, you are telling Java that you don't want to terminate and control continues with the calling method, which prints "peace".

I think you are a bit confused about the divide error message. It isn't printed when the divide error occurs. You could do that yourself in your catch clause but Java won't print anything then. The error message is printed as part of the stack trace after your program terminates abnormally. If you cancel the abnormal termination by issuing a return statement in the finally clause, there will be no stack trace and no error message from Java.
 
Nitin Bhagwat
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Mike, very nice and clear explanation.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!