DEV Community

Cover image for Learn C#: Handle Exceptions for More Reliable Code
Taizy
Taizy

Posted on

Learn C#: Handle Exceptions for More Reliable Code

Exception handling is a critical skill for any developer aiming to write robust & reliable code, particularly in scenarios involving HTTP requests. Whether you're working on a .NET based project or any other type of C# application, understanding how to handle exceptions in the context of HTTP requests is essential. In this blog, we'll explore how to use the try-catch block to manage exceptions effectively when making an HTTP request using an example.

In the following example, we use the try-catch block to handle exceptions when making an HTTP request using the HttpClient class. The code attempts to send an HTTP GET request to an invalid URL. If the response status code indicates a failure, a HttpRequestException is thrown with a descriptive error message. Otherwise, if the response is successful, a success message is printed to the console.

try
{
    using (HttpClient httpClient = new HttpClient())
    {
        string invalidUrl = "https://example.com/nonexistent-page";
        HttpResponseMessage response = await httpClient.GetAsync(invalidUrl);

        if (!response.IsSuccessStatusCode)
        {
            throw new HttpRequestException($"Failed to fetch data.\nStatus code: {response.StatusCode}");
        }
        else
        {
            Console.WriteLine("Request was successful!");
        }
    }
}
catch (HttpRequestException ex)
{
    Console.WriteLine($"Caught an HttpRequestException: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"Caught an unexpected exception: {ex.Message}");
}
Enter fullscreen mode Exit fullscreen mode

Image description

I encourage you to replace the invalidUrl with a valid URL to witness a successful request. This will help you observe how the try-catch block manages exceptions & how the code behaves when dealing with different HTTP responses.

If you're looking to enhance your understanding of C# for other similar programming concepts, I invite you to explore my 'Learn C#' GitHub repository at: https://github.com/snrelghgub/LearnCSharp.

Top comments (0)