WPF - 异常处理

异常是在执行程序期间遇到的任何错误情况或意外行为.由于许多原因可以引发异常,其中一些如下:

  • 代码或代码中的错误您调用的(例如共享库),

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

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

语法

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

  • 尝试 : 在这个区块中,程序识别出某种引起异常的条件.

  • catch :  catch关键字表示捕获异常. try 块之后是一个或多个 catch 块,以便在您要处理问题的程序中的地方捕获异常处理程序的异常.

  • 最后 :  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 
}

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

Hierarchy

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

  • ApplicationException类 : 它支持程序生成的异常.当开发人员想要定义异常时,应该从该类派生类.

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

Hierarchy

下表列出了运行时提供的标准异常以及创建派生类的条件.

异常类型基本类型描述
异常 对象所有例外的基类.
SystemException 异常所有运行时生成的错误的基类.
IndexOutOfRangeException SystemException仅在数组索引不正确时才被运行时抛出.
NullReferenceException SystemException投掷n仅在引用空对象时由运行时运行.
AccessViolationException SystemException仅在访问无效内存时由运行时抛出.
InvalidOperationException SystemException处于无效状态时由方法抛出.
ArgumentException SystemException所有参数例外的基类.
ArgumentNullException ArgumentException由不允许参数为null的方法抛出.
ArgumentOutOfRangeException ArgumentException由验证参数在给定范围内的方法抛出.
ExternalException SystemExceptione的基类发生或针对运行时之外的环境的xceptions.
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(); 
            } 
         } 
      } 
   }
}

编译并执行上述内容时代码,它将生成以下窗口,其中文本显示在文本框中.

异常处理输出

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

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(); 
            } 
         } 
      } 
   }
}

执行时引发异常上面的代码,它将显示以下消息.

异常消息

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