title: Can't catch null_value_not_allowed exception in postgresql 9.3
body: <p>I was wondering if I am missing something obvious here. I have a function that defines a table name and then goes to query that table in an execute clause. However if there are no data in the main table (one_min, fifteen_min etc) I get back a null_value_not_allowed exception with code 22004. When I try a handler around the exception, it seems to completely by pass it and still die. I tried wrapping the bigger if condition around out with still no luck. </p>
  
  <pre><code>CREATE OR REPLACE FUNCTION loadresults(force_update boolean)
    RETURNS date AS
  $BODY$
  
  declare 
  inter int;
  startdate date;
  table_name varchar(50);
  
  BEGIN
  
  select 1440 / avg(array_length(intervals,1))::int into inter from temptable;
  
  Case inter
      when 1 then 
      table_name := 'one_min';
      when 15 then 
      table_name := 'fifteen_mins';
      when 30 then 
      table_name := 'half_hour';
      when 60 then 
      table_name := 'one_hour';
      else 
         raise EXCEPTION 'I do not recognise the interval %', inter ;
  end case;
  
  SET CONSTRAINTS ALL DEFERRED ;
  
  
  if force_update is true then 
      select min(sday) into startdate from temptable ;
  else
      begin
          execute ' select max(sday) from ' || table_name
               || ' where (orgid,householdid) in
                   (select orgid, householdid from temptable limit 1 )'
          into startdate ;
      EXCEPTION when null_value_not_allowed then 
          select min(sday) into startdate from temptable; 
      end;
  end if;
  return startdate;
  END;
  $BODY$
  LANGUAGE plpgsql VOLATILE;
  </code></pre>
  
  <p>Given that all the tables exist and work fine - the function carries on to load the data - and it works fine when the force_flag is true.<br>
  When the force_update flag is false and there are no data in the one_min table, I get this error back:</p>
  
  <pre><code>ERROR: query string argument of EXECUTE is null
  SQL state: 22004
  Context: PL/pgSQL function loadresults(boolean) line 39 at EXECUTE statement
  </code></pre>
  
  <p>This points to the execute statement where the query will not return any values.
  Any ideas why that might happen? I'd rather keep the error handling within Postgres rather than my remaining code.</p>
  
  <p><strong>Update</strong> <br>
  I have now updated the query in the execute clause with this one:</p>
  
  <pre><code>execute ' select coalesce(res, tem) from ' ||
   ' (select max(sday) as res from ' || table_name  || ' 
  where (orgid,householdid) in (select orgid, householdid from temptable limit 1 )) t1, 
  (select min(sday) as tem from temptable) m ' into startdate ;
  </code></pre>
  
  <p>This seems to do the trick as the exception is not raised. I would still like to understand why the exception can't be caught. </p>