1. 异常的概念
异常是程序在运行时出现的错误情况。它们中断程序的正常执行流,可以通过异常处理机制来捕获和处理异常,以便程序能够继续运行或适当地终止。
-
常见异常类型
System.NullReferenceException
:访问空对象引用。System.IndexOutOfRangeException
:数组索引超出范围。System.DivideByZeroException
:除数为零。
-
异常的层次结构
异常类派生自System.Exception
类,常见的异常类包括System.ApplicationException
和System.SystemException
。
2. try-catch语句
try-catch
语句用于捕获和处理异常。
-
基本语法
try { // 可能产生异常的代码 } catch (ExceptionType ex) { // 处理异常的代码 }
-
示例
try { int[] numbers = { 1, 2, 3 }; Console.WriteLine(numbers[5]); } catch (IndexOutOfRangeException ex) { Console.WriteLine("Index out of range: " + ex.Message); }
在这个例子中,访问数组超出范围会抛出 IndexOutOfRangeException
异常,被 catch
块捕获并处理。
3. finally块
finally
块用于执行一些必须要运行的代码,无论是否发生异常。
-
基本语法
try { // 可能产生异常的代码 } catch (ExceptionType ex) { // 处理异常的代码 } finally { // 总是执行的代码 }
-
示例
try { int number = int.Parse("abc"); } catch (FormatException ex) { Console.WriteLine("Format error: " + ex.Message); } finally { Console.WriteLine("This code runs regardless of whether an exception was thrown."); }
在这个例子中,finally
块中的代码无论是否发生异常都会执行。
4. 自定义异常
你可以定义自己的异常类,以提供更详细的错误信息。
-
自定义异常类
public class MyCustomException : Exception { public MyCustomException() { } public MyCustomException(string message) : base(message) { } public MyCustomException(string message, Exception inner) : base(message, inner) { } }
-
抛出和捕获自定义异常
public class Example { public void DoSomething(int value) { if (value < 0) { throw new MyCustomException("Value cannot be negative."); } } } // 使用自定义异常 try { Example example = new Example(); example.DoSomething(-1); } catch (MyCustomException ex) { Console.WriteLine("Custom error: " + ex.Message); }
在这个例子中,MyCustomException
是一个自定义异常类,可以在特定情况下抛出并捕获,以便提供更有意义的错误信息。