Try Catch block

  • Please help me understand this...

    -- Create table with two columns

    CREATE TABLE #Test (Names varchar(3), Col1 varchar(2)) ;

    BEGIN TRY

    -- inserting 3 cloumn values

    -- will error out

    INSERT INTO #Test

    VALUES('AAA',NULL,NULL)

    END TRY

    BEGIN CATCH

    PRINT 'Error Occurred'+ERROR_MESSAGE()

    END CATCH

    In the above code i am forcing an error and expecting the catch block to fire. But i am directly getting the error message as below.

    "Msg 213, Level 16, State 1, Line 4

    Column name or number of supplied values does not match table definition."

    Thanks.

  • Llike other languages you can not bypass a compile error with a catch block. Since the insert does not match the table definition this is generating a compile error vs a runtime error. You see similiar operation in VB or C#. If you are just trying to purposefully trigger the error try changing it to this.

    -- Create table with two columns

    CREATE TABLE #Test (Names varchar(3), Col1 varchar(2) not null) ;

    BEGIN TRY

    -- inserting 3 cloumn values

    -- will error out

    INSERT INTO #Test

    VALUES ('AAA',NULL)

    END TRY

    BEGIN CATCH

    PRINT 'Error Occurred'+ERROR_MESSAGE()

    END CATCH

    Drop table #Test

    Having not null in Col1 causes a runtime error but will compile just fine.

    Dan

    If only I could snap my figures and have all the correct indexes apear and the buffer clean and.... Start day dream here.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply