WPF - 异常处理



异常是程序执行过程中遇到的任何错误条件或意外行为。异常可能由多种原因引起,其中一些如下:

  • 代码或您调用的代码(例如共享库)中的故障;

  • 不可用的操作系统资源;

  • 公共语言运行时遇到的意外情况(例如无法验证的代码)

语法

异常能够将程序的流程从一个部分转移到另一个部分。在 .NET 框架中,异常处理包含以下四个关键字:

  • try − 在此块中,程序识别导致某些异常的特定条件。

  • catch − catch 关键字表示捕获异常。try 块之后是一个或多个catch 块,用于使用异常处理程序在程序中捕获异常,从而处理问题。

  • finally − finally 块用于执行给定的语句集,无论是否抛出异常。例如,如果您打开了一个文件,则无论是否引发异常,都必须关闭它。

  • throw − 当出现问题时,程序会抛出异常。这是使用 throw 关键字完成的。

使用这四个关键字的语法如下:

try { 
   ///This will still trigger the exception 
} 
catch (ExceptionClassName e) { 
   // error handling code 
} 
catch (ExceptionClassName e) { 
   // error handling code
}
catch (ExceptionClassName e) { 
   // error handling code 
} 
finally { 
   // statements to be executed 
}

在 try 块根据程序流程的情况可能引发多个异常的情况下,使用多个 catch 语句。

层次结构

.NET 框架中几乎所有异常类都直接或间接地派生自 Exception 类。从 Exception 类派生的最重要的异常类是:

  • ApplicationException 类 − 它支持程序生成的异常。当开发者想要定义异常时,类应该从此类派生。

  • SystemException 类 − 它是所有预定义运行时系统异常的基类。以下层次结构显示了运行时提供的标准异常。

Hierarchy

下表列出了运行时提供的标准异常以及您应该在何种情况下创建派生类。

异常类型 基类型 描述
Exception Object 所有异常的基类。
SystemException Exception 所有运行时生成的错误的基类。
IndexOutOfRangeException SystemException 仅当数组索引不正确时,才由运行时抛出。
NullReferenceException SystemException 仅当引用空对象时,才由运行时抛出。
AccessViolationException SystemException 仅当访问无效内存时,才由运行时抛出。
InvalidOperationException SystemException 当方法处于无效状态时抛出。
ArgumentException SystemException 所有参数异常的基类。
ArgumentNullException ArgumentException 由不允许参数为 null 的方法抛出。
ArgumentOutOfRangeException ArgumentException 由验证参数在给定范围内的那些方法抛出。
ExternalException SystemException 发生在运行时外部环境或以运行时外部环境为目标的异常的基类。
SEHException ExternalException 封装 Win32 结构化异常处理信息的异常。

示例

让我们来看一个简单的例子来更好地理解这个概念。首先创建一个名为WPFExceptionHandling的新 WPF 项目。

从工具箱将一个文本框拖到设计窗口。以下 XAML 代码创建一个文本框并用一些属性对其进行初始化。

<Window x:Class = "WPFExceptionHandling.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFExceptionHandling"
   mc:Ignorable = "d" 
   Title = "MainWindow" Height = "350" Width = "604">
	
   <Grid> 
      <TextBox x:Name = "textBox" HorizontalAlignment = "Left"
         Height = "241" Margin = "70,39,0,0" TextWrapping = "Wrap" 
         VerticalAlignment = "Top" Width = "453"/> 
   </Grid> 
	
</Window>

以下是使用 C# 进行异常处理的文件读取。

using System; 
using System.IO; 
using System.Windows;

namespace WPFExceptionHandling { 

   public partial class MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
         ReadFile(0); 
      }
		
      void ReadFile(int index) { 
         string path = @"D:\Test.txt"; 
         StreamReader file = new StreamReader(path); 
         char[] buffer = new char[80]; 
			
         try { 
            file.ReadBlock(buffer, index, buffer.Length); 
            string str = new string(buffer); 
            str.Trim(); 
            textBox.Text = str; 
         }
         catch (Exception e) {
            MessageBox.Show("Error reading from "+ path + "\nMessage = "+ e.Message);
         } 
         finally { 
            if (file != null) { 
               file.Close(); 
            } 
         } 
      } 
   } 
}

编译并执行上述代码后,它将生成一个窗口,其中文本框内显示文本。

Exceptional Handling Output

当引发异常或手动抛出异常(如下面的代码所示)时,它将显示一个带有错误的消息框。

using System; 
using System.IO; 
using System.Windows;

namespace WPFExceptionHandling {
 
   public partial class MainWindow : Window {
	
      public MainWindow() { 
         InitializeComponent(); 
         ReadFile(0); 
      } 
		
      void ReadFile(int index) { 
         string path = @"D:\Test.txt"; 
         StreamReader file = new StreamReader(path); 
         char[] buffer = new char[80]; 
			
         try { 
            file.ReadBlock(buffer, index, buffer.Length); 
            string str = new string(buffer); 
            throw new Exception(); 
            str.Trim(); 
            textBox.Text = str; 
         }
         catch (Exception e) { 
            MessageBox.Show("Error reading from "+ path + "\nMessage = "+ e.Message); 
         } 
         finally { 
            if (file != null) { 
               file.Close(); 
            } 
         } 
      } 
   } 
}

当执行上述代码时引发异常时,它将显示以下消息。

Exception Message

我们建议您执行上述代码并试验其功能。

广告
© . All rights reserved.