# Error Handling

|                                   System Errors                                   |                                       Custom Errors                                       |
| :-------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------: |
| it can be viewed in the `sys.messages` system-view and are defined by SQL Server. | to add a custom error message to the`sys.messages`stored procedure`sp_addmessage`is used. |
|                                                                                   |       they are generated by T-SQL custom code based on your code or business logic.       |

```sql
EXEC sp_addmessage message_id, severity,
N'error_message'
GO;
```

> **message\_id** is of `integer` type and ranges from 50,001 to 2,147,483,647.\
> **severity** is of `smallint` type and ranges from 1 through 25.

### Raising Error with `RAISERROR`

`RAISERROR` allows SQL server to generate an error that could be caught by the calling process.

```sql
RAISERROR ( { msg_id | msg_str | @local_variable }  
    { ,severity ,state }  
    [ ,argument [ ,...n ] ] )  
    [ WITH option [ ,...n ] ]
```

### Raising Error with `THROW`

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

### `@@ERROR`

`@@ERROR` is a system variable that holds the error number of the last error occured.

* Disadvantage
  * the value that @@ERROR holds resets as a new error gets generated.

```sql
SELECT @@ERROR;
```

When working with `@@ERROR`, it is recommended to capture the error number in separate a variable as soon as error occurs.

```sql
DECLARE @error_value int;

RAISERROR(N'message', 16, 1);
SET @error_value = @@ERROR;

IF @error_value <> 0
    PRINT 'Error=' + CAST(@error_value AS VARCHAR(8));
```

{% code title="Output" %}

```sql
Msg 50000, Level 16, State 1, Line 2
Message
Error=50000
```

{% endcode %}

### TRY...CATCH

```sql
BEGIN TRY
     { sql_statement | statement_block }
END TRY
BEGIN CATCH
     { sql_statement | statement_block }
END CATCH
```
