Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • 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
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Why does the code behave so?

 
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For the following code sample:



The output is


But for the following code sample:


The output is:


Why are the output different in the above two cases, even though in both an ArithmeticException is being thrown?

Thanks,
Gitesh
[ March 18, 2008: Message edited by: Gitesh Ramchandani ]
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Switch(Gitesh's code)
case 1:
The compiler knows that the code is definitely throwing an exception from the syntax "throw new ArithmeticException();" and hence it comes to know that the next statement within that block of code is UNREACHABLE during the phase of code optimization, & thus it gives you an error!


case 2:
Here compiler cannot deduce the logic just by parsing your syntax, so it doesnt know that this will throw an ArithmeticException! Hence no compiler error!

default:
Hope that helps
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The first case does not compile, because an ArithmaticException is explicitly thrown before the System.out.println() statement, thereby making it unreachable code. The compiler can determine this.

The second case does compile, but throws the ArithmaticException at runtime, because the compiler can not pick-up on the divide-by-zero bug, and is therefor unable to determine that the System.out.prinln() statement is effectively unreachable code.

Edit: Late again...
[ March 18, 2008: Message edited by: Jelle Klap ]
 
Gitesh Ramchandani
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for help, got the point
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic