本文演示了如何使用异常筛选器来提高应用程序的可读性、可维护性和性能。
传统上,开发人员通常使用简单的 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}");
}
}
#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
】