Overflow/Underflow Exceptions

R

rnurse

Hi All,

Is there an exception, error, etc that I can check for in the event an
over-/underflow? For example, trying to put 129 into a byte variable.
The program will run fine. But the result will be -127.

Thanks.
 
I

IchBin

Hi All,

Is there an exception, error, etc that I can check for in the event an
over-/underflow? For example, trying to put 129 into a byte variable.
The program will run fine. But the result will be -127.

Thanks.
Roedy has something on this:
http://mindprod.com/jgloss/overflow.html

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA http://weconsultants.phpnet.us
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor, Regular Guy (1952-)
 
P

Paul Davis

The problem occurs because the cast that lets the code compiles
implicitly auto-masks the bits.
For example, with the values you mentioned.
byte b = 129;
will generate a compiler error (Type Mismatch).
but, adding the cast lets it compile:
byte b = (byte)129;

To see this a little better, create a class with the following method
to show bits in a byte:
public void testConvert(int val){
byte b = (byte)val;
for(int i = 7;i>=0;i--){
System.out.print( (b>>i)&1);
}
System.out.println("");
System.out.println(b);
}
then disassemble it with: javap -s -c -classpath $CLASSPATH
yourClassName

You will see the following:
public void testConvert(int);
Signature: (I)V
Code:
0: iload_1
1: i2b
2: istore_2
3: bipush 7
5: istore_3
....

take note of the mnemonic "i2b", (integer to byte) (opcode 0x91) this
converts the integer with the rule intVal & 0xFF. This actually ignores
the sing of the incoming value. The reason you see the negative number
is because "byte" is a signed type, so when the high bit is on, you get
a negative number.
So, I afraid that if you want an exception to occur in this case, you
may want to replace casts with a method call, and let the method throw
the exception.
Along the lines of:
private byte int2Byte(int val){
byte b = (byte)val;
if( (b&0xFF) != val){
throw new RuntimeException("integer too big");
}
return b;
}
Change the 0xFF to 0x7F to overflow your 129 value (129 does not really
overflow a byte)

hth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top