Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Throw (T-SQL)

Throw (T-SQL):

Before SQL server 2012 release tray…catch block used to handle error with RAISERROR.

SQL Server 2012 introduced the THROW statement. You now have a replacement for RAISERROR, the THROW statement, which makes it easier than ever to capture the error-related data.

Throw Statement:

Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server (SQL Server 2012+)

You don’t have to specify any parameters and the results are more accurate. You simply include the statement as is in the CATCH block.

NOTE: You can use the THROW statement outside of the CATCH block, but you must include parameter values to do so

Syntax:

THROW[ { error_number |@local_variable },
        {message | @local_variable },
        {state | @local_variable } ]
[ ;]

Arguments:

Error number: integer Constant or variable that represents exception must be greater than or equal to 50000 and must be less than 2147483647.

Message: ii string or variable Nvarchar (2048), describes the exception.

State: tiny integer constant or variable between 0 to 255 ,indicates state to associate message.

 

Example:

-- =============================================
-- Author:                     Nagnath Kendre
-- Create date: <Create Date,,>
-- Description: Insert's Emplyee Detail, exception handlled with try catch block and throw
-- =============================================
CREATE PROCEDURE InsertEmplyeeDetail_SP
            -- Add the parameters for the stored procedure here
            @EmployeeName Nvarchar(250),
            @Country Nvarchar(50),
            @PrimaryLanguage Nvarchar(150),
            @CompanyPlantNvarchar(150),
            @ManagerId int
AS
BEGIN
            -- SET NOCOUNT ON added to prevent extra result sets from
            -- interfering with SELECT statements.
 SET NOCOUNT ON;
 BEGIN TRY
 BEGIN TRANSACTION
  INSERT INTO Employee
([EmployeeName],[Country],[PrimaryLanguage],[CompanyPlant],[ManagerId],[CreatedDate])
 VALUES (@EmployeeName,@Country,@PrimaryLanguage,@CompanyPlantNvarchar,@ManagerId,\
,GETDATE() )
 
 COMMIT TRANSACTION;
 END TRY
 
BEGIN CATCH
IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
 
    DECLARE @ErrorNumber INT = ERROR_NUMBER();
    DECLARE @ErrorLine INT = ERROR_LINE();
 
    PRINT 'Actual error number: ' + CAST(@ErrorNumber AS VARCHAR(10));
    PRINT 'Actual line number: ' + CAST(@ErrorLine AS VARCHAR(10));
 
    THROW;
 
END CATCH
 
END
GO

Invalid entry,please enter valid data.

Loading