title: PostgreSQL Function: Capture exception and go next in LOOP
body: <p>I am trying to implement a function which essentially computes different aggregated values and inserts these values as a row in a new table.</p>
  <p>Something like this:</p>
  <pre><code>CREATE OR REPLACE FUNCTION myfunction() RETURNS void AS 
  $$
  DECLARE 
  
      table_name CHARACTER VARYING(100);
      loop_var RECORD;
  
      var1 INT;
      var2 INT;
      var3 INT;
    
  BEGIN
  
      FOR loop_var IN (SELECT user FROM users) LOOP
      SELECT COUNT(*) INTO var1 FROM another_table WHERE user = registro.user;
      SELECT COUNT(*) INTO var2 FROM another_table WHERE user = registro.user;
      SELECT COUNT(*) INTO var3 FROM another_table WHERE user = registro.user;
      INSERT INTO new_table VALUES(loop_var.user,var1,var2,var3);
      END LOOP;
      
  END
  $$ language 'plpgsql'
  ;
  </code></pre>
  <p><strong>QUESTION:</strong></p>
  <p>I would like to capture the exceptions when there is a problem in any of my select statements or in any of my inserts. I would like to capture the exception, skip that user (if there is any issue with it) and continue the loop.</p>
  <p>I have tried using <code>EXCEPTION WHEN raise_exception THEN '% : %', SQLSTATE, SQLERRM;</code> but it did not work. Also, if I use RAISE EXCEPTION, the loop does not continue.</p>
  <p>Could you please help me on the sintaxi I should follow in order to achieve the above goals?</p>