BEGIN TRY and BEGIN CATCH - SQL Server to PostgreSQL Migration

In SQL Server, you can use BEGIN TRY and BEGIN CATCH blocks to handle exceptions. In PostgreSQL, you can use the EXCEPTION section of BEGIN-END block.

Consider a sample table with a unique constraint:

   -- Sample table
   CREATE TABLE colors (name VARCHAR(30) PRIMARY KEY NOT NULL);

SQL Server:

  BEGIN TRY
    -- Insert the first row
    INSERT INTO colors VALUES('White');
    -- Insert a duplicate that violates the constraint    
    INSERT INTO colors VALUES('White');
  END TRY
  BEGIN CATCH
    PRINT 'Error'
  END CATCH
  GO
  /* Result: Error */

PostgreSQL:

  DO $$
  BEGIN
    -- Insert the first row
    INSERT INTO colors VALUES('White');
    -- Insert a duplicate that violates the constraint    
    INSERT INTO colors VALUES('White');
  EXCEPTION WHEN OTHERS THEN
    RAISE NOTICE 'Error';
  END $$;
  /* Result: NOTICE:  Error */

For more information, see SQL Server to PostgreSQL Migration.