'postgres create database fails within script

please can someone advise on my mistake. I am trying to script the db creation script, which seems to fail. I am sure i missing something basic. thank alot

DO
$do$
BEGIN
   IF NOT EXISTS (
      SELECT FROM pg_catalog.pg_roles  -- SELECT list can be empty for this
      WHERE  rolname = 'test') THEN
      create user test password 'b6e29d';
      PERFORM dblink_exec('', 'CREATE DATABASE test owner test');
      EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
   END IF;
END
$do$;
ERROR:  syntax error at or near "EXCEPTION"
LINE 9:       EXCEPTION WHEN duplicate_database THEN RAISE NOTICE '%...


Sources

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

Source: Stack Overflow

Solution Source