.NET C#基础教程第25天:使用异常筛选器

作者:微信公众号:【架构师老卢】
6-10 10:42
55

概述:介绍本文演示了如何使用异常筛选器来提高应用程序的可读性、可维护性和性能。学习目标传统异常处理的问题使用筛选器进行高效的异常处理。开发人员的先决条件基本了解 C# 编程语言。开始传统异常处理的问题传统上,开发人员通常使用简单的 catch 块来处理异常,并使用条件逻辑来处理特定的异常类型。请在下面找到演示传统方法的代码片段try {     // Perform an operation } catch (Exception ex) {     if (ex is InvalidOperationException || ex is ArgumentNullException)  

介绍

本文演示了如何使用异常筛选器来提高应用程序的可读性、可维护性和性能。

学习目标

  • 传统异常处理的问题
  • 使用筛选器进行高效的异常处理。

开发人员的先决条件

  • 基本了解 C# 编程语言。

开始

传统异常处理的问题

传统上,开发人员通常使用简单的 catch 块来处理异常,并使用条件逻辑来处理特定的异常类型。请在下面找到演示传统方法的代码片段

try  
{  
    // Perform an operation  
}  
catch (Exception ex)  
{  
    if (ex is InvalidOperationException || ex is ArgumentNullException)  
    {  
        // Handle the specific exceptions  
    }  
    else  
    {  
        throw;  // Rethrow the exception if it's not one we're specifically handling  
    }  
}

将条件语句与 if 块一起使用会创建一个难以维护且看起来不太可读的代码。

使用筛选器进行高效的异常处理

请在下面找到上一个代码片段的重构版本

try  
{  
    // Perform an operation  
}  
catch (Exception ex) when (ex is InvalidOperationException || ex is ArgumentNullException)  
{  
    // Handle only InvalidOperationException or ArgumentNullException  
}

上述方法提高了代码的可读性和可维护性。除此之外,它还增强了性能,因为只有当筛选器评估为真时才会执行 catch 块,因为捕获异常是一项代价高昂的操作。只有当过滤器返回 true 时,才会捕获堆栈跟踪,

完整代码

创建另一个名为的类,并添加以下代码片段ExceptionFilters

public static class ExceptionFilters  
{  
    public static void MultipleCatch(string input)  
    {  
        try  
        {  
            ProcessInput(input);  
        }  
        catch (Exception ex)  
        {  
            if (ex is InvalidOperationException || ex is ArgumentNullException)  
            {  
                Console.WriteLine($"Conventional Handling: Caught {ex.GetType().Name}");  
            }  
            else  
            {  
                throw;  
            }  
        }  
    }  
    public static void GoodWay(string input)  
    {  
        // Using exception filters  
        try  
        {  
            ProcessInput(input);  
        }  
        catch (Exception ex) when (ex is InvalidOperationException || ex is ArgumentNullException)  
        {  
            Console.WriteLine($"Exception Filters Handling: Caught {ex.GetType().Name}");  
        }  
    }  
  
    public static void ProcessInput(string input)  
    {  
        if (input == null)  
            throw new ArgumentNullException(nameof(input), "Input cannot be null.");  
        else if (input == "invalid")  
            throw new InvalidOperationException("Invalid input provided.");  
  
        Console.WriteLine($"Processing {input}");  
    }  
}

从 main 方法执行,如下所示

#region Day 25: Use Exception Filters  
static string ExecuteDay25()  
{  
    // Using conventional exception handling  
    // This will cause ArgumentNullException  
    ExceptionFilters.MultipleCatch(null);  
  
  
    // Reset input for valid processing  
    ExceptionFilters.GoodWay("Valid input");  
  
  
    // This input will cause InvalidOperationException  
    ExceptionFilters.GoodWay("invalid");  
  
    return "Executed Day 25 successfully..!!";  
}  
  
#endregion

控制台输出

Conventional Handling: Caught ArgumentNullException  
Processing Valid input  
Exception Filters Handling: Caught InvalidOperationException

源代码获取:公众号回复消息【code:87340

相关代码下载地址
重要提示!:取消关注公众号后将无法再启用回复功能,不支持解封!
第一步:微信扫码关键公众号“架构师老卢”
第二步:在公众号聊天框发送code:87340,如:code:87340 获取下载地址
第三步:恭喜你,快去下载你想要的资源吧
阅读排行