.NET Library Reference

System.Net.Sockets.SocketException

This exception is thrown when a socket-related error occurs during network operations.

Details

The SocketException class derives from IOException and provides information about socket errors. It contains a SocketErrorCode property that specifies the specific error that occurred.

Common Causes

SocketErrorCode Enum

The SocketError enumeration defines the possible errors that can occur. Some common values include:

Handling the Exception

It is crucial to handle SocketException to gracefully manage network errors in your application. You can use a try-catch block to intercept and process these exceptions.

try {
    // Network operation that might throw SocketException
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    socket.Connect("invalid.host.name", 12345);
} catch (SocketException ex) {
    // Log the exception or display an error message to the user
    Console.WriteLine($"SocketException caught: {ex.SocketErrorCode} - {ex.Message}");
    // You can also check specific error codes for different handling
    if (ex.SocketErrorCode == SocketError.ConnectionRefused) {
        Console.WriteLine("Connection refused. Ensure the server is running.");
    }
}

Related Topics