• 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

Exception and Error Q

 
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the following coding, why compiler ignores exception at line 1 and catches error at line 2.

Is it this, because of line 1 is exception, it will catch at runtime and line 2 is an error so, it will catch at compile time.

 
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Nitin,
ArithmeticException will be thrown at runtime. However, the int result which is assigned to byte is caught at compile-time. Hope that helps ya.
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The Java spec spells out which specific errors are flagged at compile time. Type safety, uninitialized variables, ambiguous member selection, and narrowing casts are examples.

Sometimes javac looks at literal values, such as in "byte b1 = 1;", which is allowed even though "1" is an int because javac knows that "1" will fit in a byte. javac may even do the arithmetic with literals at compile time, so "byte b3 = 2 / 1;" is allowed but "byte b3 = 1 + 1000;" and "byte b3 = 2 / 0;" are not. But this is done only enough to implement the special rule involving constant initializers of bytes, chars, and shorts, which is part of the check for narrowing casts. "int i = 10/0;" does not require doing the arithmetic to check for narrowing casts because the result of the / will always be an int.

I suspect that the reason Java allows 10/0 to go into execution is to allow students like us to practice handling exceptions. At any rate, that is the rule affecting your example.
 
Nitin Bhagwat
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Very nice explanation Mike, Thank you !
 
Enjoy the full beauty of the english language. Embedded in this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic