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

Exception and Error Q

 
Nitin Bhagwat
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • 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.

 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • 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.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Very nice explanation Mike, Thank you !
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic