SQLServer
exception handling
timeout exceptions
database error
SQLServer troubleshooting

How to catch SQLServer timeout exceptions

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A SQL Server timeout is usually handled in application code like any other database exception, but the useful part is identifying which timeout occurred. A command execution timeout, a connection timeout, and a connection-pool timeout do not always throw the same exception type or indicate the same underlying problem. Treating them as one category is one of the easiest ways to hide the real failure mode.

Catch Command Timeouts with SqlException

For ADO.NET code that executes a SQL command, a common pattern is to catch SqlException and inspect the error number. Command timeouts are commonly exposed as SqlException with number -2.

csharp
1using System;
2using System.Data.SqlClient;
3
4try
5{
6    using var connection = new SqlConnection(
7        "Server=localhost;Database=SalesDb;Integrated Security=true;");
8    connection.Open();
9
10    using var command = new SqlCommand(
11        "WAITFOR DELAY '00:00:05'; SELECT 1;",
12        connection);
13
14    command.CommandTimeout = 1;
15    command.ExecuteScalar();
16}
17catch (SqlException ex) when (ex.Number == -2)
18{
19    Console.WriteLine("SQL command timed out.");
20}

This lets you separate a timeout from other SQL failures such as syntax errors, permission issues, or missing tables.

Distinguish Command, Connection, and Pool Timeouts

Not every timeout means the same thing:

  • command timeout: the SQL command took too long to finish
  • connection timeout: opening the connection took too long
  • connection pool timeout: the app could not obtain a connection from the pool in time

The first often surfaces as SqlException. Pool exhaustion can appear as InvalidOperationException with a timeout message instead. That distinction matters because the fix changes completely.

For example, you might catch both:

csharp
1try
2{
3    // database work here
4}
5catch (SqlException ex) when (ex.Number == -2)
6{
7    Console.WriteLine("Command or connection timeout detected.");
8}
9catch (InvalidOperationException ex) when (ex.Message.Contains("timeout"))
10{
11    Console.WriteLine("Possible connection pool timeout.");
12}

Message matching should not be your first choice for every error, but it is sometimes necessary when the failure is not represented by a dedicated SQL error number.

Log Enough Context to Debug the Cause

Catching the exception is only the first step. Timeouts are symptoms, not root causes. Log:

  • which query or stored procedure was running
  • which timeout setting applied
  • how long the operation had been running
  • whether the failure happened on Open() or on command execution

Without that context, all timeout exceptions look identical in logs and are much harder to fix later.

If a query times out repeatedly, examine indexing, locking, blocking, and execution plans instead of only raising the timeout value.

Retry Carefully

Retries can make sense for transient connection issues, but they are risky for arbitrary command timeouts. If the command is not idempotent, retrying automatically can duplicate work or produce inconsistent state.

If you add retry logic, make the rule explicit:

csharp
1for (var attempt = 1; attempt <= 3; attempt++)
2{
3    try
4    {
5        // run safe, retryable database operation
6        break;
7    }
8    catch (SqlException ex) when (ex.Number == -2 && attempt < 3)
9    {
10        System.Threading.Thread.Sleep(500);
11    }
12}

Use retries for clearly retryable operations, not as a universal timeout bandage. A retry policy should reflect the semantics of the operation, not just the fact that a timeout happened.

Common Pitfalls

The biggest mistake is catching every Exception and calling it a timeout. SQL Server failures include many different conditions, and broad catches hide useful diagnostic detail.

Another issue is assuming every timeout comes from slow SQL. Sometimes the database is fine, but the connection pool is exhausted because connections are not being disposed properly.

Developers also often raise timeout values before checking whether the query is blocked or missing an index. A larger timeout can make the symptom quieter while the root cause remains unchanged.

Finally, be careful with automatic retries on write operations. A retry that looks harmless on a SELECT may be dangerous on an INSERT or stored procedure with side effects.

Summary

  • Catch SQL Server command timeouts with SqlException and inspect the error details.
  • Timeout number -2 is commonly used for SQL command timeout detection.
  • Distinguish query, connection, and pool timeouts because the fixes differ.
  • Log where the timeout happened and what operation was running.
  • Use retries only when the operation is safe to repeat.

Course illustration
Course illustration

All Rights Reserved.