public class Overflow {
    private static void printUnsignedByte(byte b) {
        int unsignedByte = b & 0xFF;
        System.out.print(unsignedByte);
    }

    private static byte addAndCheck(byte x, byte y)
            throws MathArithmeticException {
        long s = (long)x + (long)y;
        if (s < Byte.MIN_VALUE || s > Byte.MAX_VALUE) {
            throw new MathArithmeticException("Ueberlauf bei der Addition von ", x, y);
        }
        return (byte) s;
    }

    public static void main(String[] args) {
        byte b = 127;
        System.out.print(b + " + 3 = ");
        b = (byte) (b + 3);
        System.out.println(b);
        System.out.flush();
        //Hier addAndCheck
        try {
            b = 127;
            b = addAndCheck(b, (byte) 3);
            System.out.println("127 + 3 = " + b);
        } catch (MathArithmeticException e) {
            System.err.println(e.getMessage());
        }
        System.err.flush();
        //Beispiel aus der Uebung
        byte b1 = (byte) 128;
        printUnsignedByte(b1);
        System.out.print(" + ");
        printUnsignedByte(b1);
        System.out.print(" = ");
        printUnsignedByte((byte) (b1 + b1));
    }

    private static class MathArithmeticException extends ArithmeticException {
        private String message = "";

        MathArithmeticException(String ueberlauf_bei_der_addition, int x, int y) {
            message = ueberlauf_bei_der_addition + x + " und " + y;
        }

        /** {@inheritDoc} */
        @Override
        public String getMessage() {
            return message;
        }
    }
}
