Search code examples
exceptionstored-proceduresgoogle-bigquerybigquery-udf

Raise Exception issue in big query scripting


I would like to print the custom message as an exception error with the RAISE keyword in big query script. But, the below command lines is throwing an error at the raise command. But, if I remove the raise command it is working fine. Could you please help me how I have to raise a custom error message?? Also, to know more about the RAISE [USING MESSAGE = message];.

BEGIN
SELECT 1/0; -- attempts to divide by zero
RAISE USING message = "divisible with zero is not allowed.";
EXCEPTION WHEN ERROR THEN
SELECT FORMAT("Hey, you. When you executed %s at %s, it caused an error: %s. Please don't do that.", @@error.statement_text, @@error.formatted_stack_trace, @@error.message);
END;

Solution

  • The RAISE statement must only be used within an EXCEPTION clause. The RAISE statement will re-raise the exception that was caught, and preserve the original stack trace.

    Ref: https://cloud.google.com/bigquery/docs/reference/standard-sql/scripting#raise

    So if you want to raise an exception with custom message, it should be:

    BEGIN
    SELECT 1/0; -- attempts to divide by zero
    EXCEPTION WHEN ERROR THEN
    RAISE USING message = FORMAT("Hey, you. When you executed %s at %s, it caused an error: %s. Please don't do that.", @@error.statement_text, @@error.formatted_stack_trace, @@error.message);
    END;