Sobes.tech
Middle

Kuidas saab koodis kasutades await erandeid püüda?

sobes.tech AI

Vastus AI-lt

Exceptions in code using await are caught by standard try...catch blocks.

Example:

public async Task GetDataAsync()
{
    try
    {
        // Call to an asynchronous operation that may throw an exception
        var result = await SomeService.FetchDataFromApiAsync();
        // Handling successful result
    }
    catch (UnauthorizedAccessException ex)
    {
        // Handling specific exception (e.g., lack of permissions)
        Console.WriteLine($"Authorization error: {ex.Message}");
    }
    catch (HttpRequestException ex)
    {
        // Handling HTTP request exception (e.g., network issues)
        Console.WriteLine($"HTTP request error: {ex.Message}");
    }
    catch (Exception ex)
    {
        // Handling any other unhandled exceptions
        Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        // Additional actions: logging, user notification, etc.
    }
}

If the asynchronous operation pointed to by await throws an exception, the direct code flow is interrupted, and control is transferred to the corresponding catch block in the same asynchronous function (or the caller). Without await, an exception from an asynchronous operation will not be caught by the calling function until the task/operation is completed and its result/exception is requested (e.g., via .Result or .Wait(), which is not recommended). await effectively "unwraps" the exception from the task and rethrows it, making catching with try...catch a common way possible.