7.1 try-catch-finally 详细讲解
在 C# 中,异常处理是确保程序稳定性和健壮性的重要机制。try-catch-finally
结构是 C# 中用于捕获和处理异常的基本语法。下面是对 try-catch-finally
的详细讲解,包括其优点、缺点以及代码示例。
基本语法
csharp
try
{
// 可能会引发异常的代码
}
catch (ExceptionType1 ex1)
{
// 处理 ExceptionType1 类型的异常
}
catch (ExceptionType2 ex2)
{
// 处理 ExceptionType2 类型的异常
}
finally
{
// 无论是否发生异常都会执行的代码
}
优点
- 提高程序的健壮性:通过捕获和处理异常,程序可以在遇到错误时继续运行或优雅地终止。
- 分离错误处理逻辑:将错误处理逻辑与正常业务逻辑分离,使代码更清晰和易于维护。
- 资源管理:
finally
块确保资源(如文件句柄、数据库连接等)在任何情况下都能被正确释放。 - 灵活性:可以捕获和处理不同类型的异常,提供更细粒度的错误处理。
缺点
- 性能开销:异常处理本身有一定的性能开销,频繁使用可能会影响程序性能。
- 过度捕获:过度捕获异常可能导致隐藏潜在的错误,使调试变得困难。
- 嵌套复杂:复杂的嵌套
try-catch
结构可能导致代码难以理解和维护。 - 资源泄漏:如果
finally
块中没有正确处理资源释放,可能会导致资源泄漏。
代码示例
以下是一些使用 try-catch-finally
结构的示例代码,展示了如何捕获和处理异常。
1. 基本用法
csharp
using System;
class Program
{
static void Main()
{
try
{
int result = Divide(10, 0);
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Cannot divide by zero.");
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: " + ex.Message);
}
finally
{
Console.WriteLine("Execution of try-catch block completed.");
}
}
static int Divide(int numerator, int denominator)
{
return numerator / denominator;
}
}
2. 使用多个 catch
块
csharp
using System;
class Program
{
static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // 引发 IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Error: Index out of range.");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Cannot divide by zero.");
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: " + ex.Message);
}
finally
{
Console.WriteLine("Execution of try-catch block completed.");
}
}
}
3. 使用 finally
块释放资源
csharp
using System;
using System.IO;
class Program
{
static void Main()
{
StreamReader reader = null;
try
{
reader = new StreamReader("example.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Error: File not found.");
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: " + ex.Message);
}
finally
{
if (reader != null)
{
reader.Close();
Console.WriteLine("File closed.");
}
}
}
}
4. 使用 using
语句简化资源管理
csharp
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
using (StreamReader reader = new StreamReader("example.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Error: File not found.");
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: " + ex.Message);
}
}
}
通过这些示例,您可以更好地理解和使用 try-catch-finally
结构来处理异常。