• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

about finally and return statement

 
Ranch Hand
Posts: 188
IntelliJ IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Sub {
static int read (int i) {
try {
if (i<5) return 5/i ;
else return i*5 ;
} catch (ArithmeticException e) {
System.out.println ("ArithmeticException") ;
} finally {
System.out.println("Finally");
return i+100 ; // look here
}
}
public static void main (String [ ] args) {
System.out.println (read(4)) ;
System.out.println (read(10)) ;
}
}

Why does it give a compile time error if return i+100 is commented when one of the above return statements are going to be executed
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider what happens if read is called with a parameter of zero.

We enter the try block and find that i is less than 5, so we try to return 5/i. But in evaluating 5/i, we throw an ArithmeticException (because we're dividing by zero). When the exception is thrown, the code in the try block stops executing, and -- without returning anything -- execution transfers to the catch block and then the finally block. At that point, the exception has been handled, but we're still in the method, which must return an int...

(See how nice this looks with Code Tags? )
 
Sudarshan Sreenivasan
Ranch Hand
Posts: 188
IntelliJ IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks alot .... got the point and nice tip !!
 
Opportunity is missed by most people because it is dressed in overalls and looks like work - Edison. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic