Effective Error Handling Techniques in C# and .NET

Effective Error Handling Techniques in C# and .NET

??? ?? ???? C# ?? .NET ?? Effective Error Handling Techniques ??????? ?????? ?????.

Error handling ??????? software development ??? ?????? ??????? ????????. Proper error handling techniques use ???? application ??? reliability ?? user experience ?? optimize ????? ???????. C# ?? .NET frameworks ??? error handling mechanisms provide ?????.

Key Error Handling Techniques

1. Use Try-Catch Blocks

Try-catch blocks ?????? ???? predictable errors handle ?????.

Example:

try
{
    // Code that may throw an exception
    int result = 10 / int.Parse("0");
}

catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero.");
}

catch (FormatException ex)
{
    Console.WriteLine("Invalid input format.");
}        

2. Use Finally Block

This is particularly useful for releasing resources like open files, network connections, or database connections. If an exception occurs during processing, these resources might not be closed properly, leading to leaks or unexpected behavior. The finally block ensures proper cleanup regardless of the execution flow.

Example:

StreamReader reader = null;
try
{
    reader = new StreamReader("file.txt");
    // Code that may throw an exception
}

catch (IOException ex)
{
    Console.WriteLine("An IO error occurred.");
}

finally
{
    if (reader != null)
    {
        reader.Close();
    }
}        

3. Throwing Exceptions

Custom exceptions create ???? meaningful error messages provide ?????.

Example:

public class InvalidAgeException : Exception
{
    public InvalidAgeException(string message) : base(message) { }
}

public class User
{
    public int Age { get; set; }
    public void SetAge(int age)
    {
        if (age < 0 || age > 120)
        {
            throw new InvalidAgeException("Age must be between 0 and 120.");
        }
        Age = age;
    }
}        

4. Using Exception Filters

Exception filters use ???? specific conditions satisfy ??? exceptions capture ?????.

Example:

try
{
    // Code that may throw an exception
}

catch (Exception ex) when (ex.Message.Contains("specific keyword"))
{
    Console.WriteLine("Caught exception with specific keyword.");
}        

5. Global Exception Handling

Global exception handling use ???? unhandled exceptions capture ?????.

Example: ASP.NET Core

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
    // Other middleware
}        

Error Handling Middleware:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;
    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }

        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception ex)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        var result = JsonConvert.SerializeObject(new { error = ex.Message });
        return context.Response.WriteAsync(result);
    }
}        

6. Logging Exceptions

Exceptions log ???? future debugging ?? monitoring facilitate ?????.

Example: Using Serilog

public class Program
{
    public static void Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Console()
            .WriteTo.File("logs\\myapp.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();

        try
        {
            Log.Information("Starting up");
            CreateHostBuilder(args).Build().Run();
        }

        catch (Exception ex)
        {
            Log.Fatal(ex, "Application start-up failed");
        }

        finally
        {
            Log.CloseAndFlush();
        }
    }
}        

7. Using Data Annotations for Validation

Data annotations use ???? model validation errors handle ?????.

Example:

public class User
{
    [Required(ErrorMessage = "Name is required")]
    [StringLength(50, ErrorMessage = "Name length can't be more than 50.")]
    public string Name { get; set; }

    [Range(0, 120, ErrorMessage = "Age must be between 0 and 120.")]
    public int Age { get; set; }

}        

Conclusion

Effective error handling techniques, application ??? reliability ?? user experience ?? enhance ????? ???????. Try-catch blocks, finally blocks, throwing exceptions, exception filters, global exception handling, logging, ?? data annotations ??? techniques use ???? robust error handling mechanism ???? build ?????. C# ?? .NET frameworks ?? tasks complete ????? ??? support ???? ??????.

??? ????????? ???? useful software development tips and tricks ????? ???? ????.

#SoftwareDevelopment #CSharp #DotNet #ErrorHandling #Logging #ExceptionHandling #GlobalExceptionHandling #Validation #BestPractices

要查看或添加评论,请登录

Malinda Gamage的更多文章

社区洞察

其他会员也浏览了