Raising runtime errors

Errors and warnings are easy to raise in the PHP runtime. This tutorial shows how to raise an error by passing a ResourceBundle that contains the error message to the PHP runtime.

1. Add the following Java™ code to the BigDecimalExtension class:

public class BigDecimalResoures extends ListResourceBundle {
        public Object[][] getContents() {
                return contents;
        }
        final Object[][] contents = {
                { "CannotDivideByZero", "Cannot divide by zero!" },
        };
}

@XAPIFunction("divide_bigdecimal")
public void divide(RuntimeContext ctxt) {
        BigDecimal arg1 = new BigDecimal(ctxt. 
        getStringArgument(0).getString());
        BigDecimal arg2 = new BigDecimal(ctxt. 
        getStringArgument(1).getString());
        if (arg2.intValue() == 0) {
                RuntimeServices runtimeServices = getRuntimeServices();
                ErrorService errors = runtimeServices.getErrorService();
                errors.raiseError(XAPIErrorType.Warning, new BigDecimalResoures(),
                "CannotDivideByZero", new Object[] { });
                // Raising an error throws an exception to terminate the script!
        } else {
                BigDecimal result = arg1.divide(arg2, this.roundingMode);
                ctxt.setReturnValue(result.toString());
        }
}

2 Change the sample.php code to exercise the new function.

<?php
$arg0 = '111111111111111';
$arg1 = '000000000000000';
$result = divide_bigdecimal($arg0, $arg1);
echo 'The answer is: '.$result;
?>

3. Run the IBM® WebSphere® sMash application and point a Web browser at http://localhost:8080/sample.php. The Web browser displays an error message stating that the script cannot divide by zero.

The example uses the ErrorService interface to raise the error.

Notice that the XAPIErrorType.Warning has been used here. This is compatible with the PHP programming practice which reserves XAPIErrorType.Error for unrecoverable errors. When choosing the XAPIErrorType to use, consider the definitions provided in the PHP documentation.

Version 1.1.31300