这两个代码片段在功能上是等效的,但它们的实现方式略有不同。
### 第一个代码片段
```csharp
using System;
namespace ExceptionFilterDemo
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number: ");
int number = int.Parse(Console.ReadLine());
// Intentionally cause a divide by zero exception
int result = 100 / number;
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex) when (ex.Message.Contains("divide by zero"))
{
Console.WriteLine("Caught a divide by zero exception: Division by zero is not allowed.");
}
catch (FormatException ex) when (ex.Message.Contains("Input string was not in a correct format"))
{
Console.WriteLine("Caught a format exception: Please enter a valid number.");
}
catch (Exception ex)
{
Console.WriteLine($"Caught an unexpected exception: {ex.Message}");
}
}
}
}
```
### 第二个代码片段
```csharp
using System;
namespace ExceptionFilterDemo
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number: ");
int number = int.Parse(Console.ReadLine());
// Intentionally cause a divide by zero exception
int result = 100 / number;
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
if (ex.Message.Contains("divide by zero"))
{
Console.WriteLine("Caught a divide by zero exception: Division by zero is not allowed.");
}
else
{
throw; // Re-throw the exception if the condition is not met
}
}
catch (FormatException ex)
{
if (ex.Message.Contains("Input string was not in a correct format"))
{
Console.WriteLine("Caught a format exception: Please enter a valid number.");
}
else
{
throw; // Re-throw the exception if the condition is not met
}
}
catch (Exception ex)
{
Console.WriteLine($"Caught an unexpected exception: {ex.Message}");
}
}
}
}
```
### 比较
1. **异常过滤器 (`when` 子句)**:
- 第一个代码片段使用了 C# 6.0 引入的异常过滤器 (`when` 子句),这使得异常处理更加简洁和直观。
- 第二个代码片段使用了传统的 `if` 条件检查,并在条件不满足时重新抛出异常。
2. **代码简洁性**:
- 第一个代码片段更简洁,因为它直接在 `catch` 语句中使用了 `when` 子句来过滤异常。
- 第二个代码片段稍微冗长一些,因为它在 `catch` 块内部使用了 `if` 语句来检查条件,并在不满足条件时重新抛出异常。
3. **性能**:
- 异常过滤器 (`when` 子句) 在性能上可能稍微优于传统的 `if` 检查,因为 `when` 子句在异常发生时会立即进行过滤,而不会进入 `catch` 块。
4. **可读性**:
- 第一个代码片段的可读性更高,因为它直接在 `catch` 语句中表达了过滤条件。
- 第二个代码片段的可读性稍差,因为它在 `catch` 块内部使用了 `if` 语句,并且需要重新抛出异常。
综上所述,虽然这两个代码片段在功能上是等效的,但第一个代码片段使用了更现代和简洁的异常过滤器语法,因此在可读性和简洁性上更胜一筹。