Handling Errors

If your UDx encounters an unrecoverable error, it should instantiate and throw a UdfException. The exception causes the transaction containing the function call to be rolled back.

The UdfException constructor takes a numeric code (which can be anything you want since it is just reported in the error message) and an error message string. If you want to report additional diagnostic information about the error, you can write messages to a log file before throwing the exception (see Writing Messages to the Log File).

The following code fragment demonstrates adding error checking to the Add2ints UDSF example (shown in Java Example: Add2Ints). If either of the arguments is NULL, the processBlock() method throws an exception.

        @Override
        public void processBlock(ServerInterface srvInterface,
                                 BlockReader argReader,
                                 BlockWriter resWriter)
                    throws UdfException, DestroyInvocation
        {
            do {
                // Test for NULL value. Throw exception if one occurs.
                if (argReader.isLongNull(0) || argReader.isLongNull(1) ) {
                    // No nulls allowed. Throw exception
                    throw new UdfException(1234, "Cannot add a NULL value");
                }

Note: This example isn't realistic, since you would likely just replace the NULL value with a zero or return a NULL value. Your UDx should only throw an exception if there is no way to compensate for the error.

When your UDx throws an exception, the side process running your UDx reports the error back to Vertica and exits. Vertica displays the error message contained in the exception and a stack trace to the user:

=> SELECT add2ints(2, NULL);
ERROR 3399:  Failure in UDx RPC call InvokeProcessBlock(): Error in User Defined Object [add2ints], error code: 1234
com.vertica.sdk.UdfException: Cannot add a NULL value
        at com.mycompany.example.Add2intsFactory$Add2ints.processBlock(Add2intsFactory.java:37)
        at com.vertica.udxfence.UDxExecContext.processBlock(UDxExecContext.java:700)
        at com.vertica.udxfence.UDxExecContext.run(UDxExecContext.java:173)
        at java.lang.Thread.run(Thread.java:662)