'Postgresql raise exception does not work as expected if used with pg_sleep

I have created one procedure which continuously check for status in one table and if the status is fail then it will raise an exception . This flow works if the fail status comes in first 7-8 runs if I keep pg_sleep as 15 seconds , but if error comes after that then the procedure does not throw error and procedure completes successfully. So I again tried the same with pg_sleep(150) and this time the procedure successfully executes in second cycle itself and I do not get error .

Edit : I want the procedure to throw error.

The procedure is as below , I have removed most of the code but the working is same

CREATE OR REPLACE PROCEDURE usp_check()
LANGUAGE 'plpgsql'
AS $BODY$
DECLARE _count integer ;
BEGIN
BEGIN
_count=1;
    WHILE _count <=2 LOOP
        PERFORM pg_sleep(150);
        _count= _count+1;
        --- Perform some action 
    END LOOP;

END;    
COMMIT;
BEGIN

    RAISE EXCEPTION 'Error:%', 'Error occurred';
END ;
END ;
$BODY$;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source