TOC

This article has been localized into Chinese by the community.

WPF應用程式:

在WPF中處理例外

如果你熟悉C#或是其他任何你可以配合WPF使用的.NET語言,那麼例外處理對你而言將不陌生:當你有一段程式碼有機會擲回例外,那麼你應該透過「try-catch」區塊包住它來優雅地處理例外。舉例來說,請思考下面的範例:

private void Button_Click(object sender, RoutedEventArgs e)
{
	string s = null;
	s.Trim();
}

顯而易見,因為我試著對一個當下是null的變數使用「Trim()」方法,這將會產生錯誤。如果你不處理這個例外,你的程式將會中止而Windows將需要去處理這個問題。如你所見,這對使用者相當不友善:

在這個場合,使用者將會因為如此單純而輕易就能避免的錯誤被迫中止你的應用程式。所以如果你知道某些東西可能出錯,你就應該使用「try-catch」區塊,例如:

private void Button_Click(object sender, RoutedEventArgs e)
{
	string s = null;
	try
	{
		s.Trim();
	}
	catch(Exception ex)
	{
		MessageBox.Show("A handled exception just occurred: " + ex.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
	}
}

然而有時候就算是最單純的程式碼也可能擲出例外,而WPF讓你全域性地處理所有未處理的例外,取代以「try-catch」區塊包覆每一行程式碼。這樣功能透過在「Application 」類別裡的「DispatcherUnhandledException」事件來達成。如果訂閱了該事件,每當有在你本身程式碼中未處理例外遭擲出時,WPF將會呼叫訂閱的方法。以下是一個基於我們剛剛討論過東西的完整例子:

<Window x:Class="WpfTutorialSamples.WPF_Application.ExceptionHandlingSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ExceptionHandlingSample" Height="200" Width="200">
    <Grid>
        <Button HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_Click">
            Do something bad!
        </Button>
    </Grid>
</Window>
using System;
using System.Windows;

namespace WpfTutorialSamples.WPF_Application
{
	public partial class ExceptionHandlingSample : Window
	{
		public ExceptionHandlingSample()
		{
			InitializeComponent();
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			string s = null;
			try
			{
				s.Trim();
			}
			catch(Exception ex)
			{
				MessageBox.Show("A handled exception just occurred: " + ex.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Warning);
			}
			s.Trim();
		}
	}
}

請注意這邊我在「try-catch」區塊外面額外呼叫了一次「Trim()」方法,所以第一次呼叫有被處理,而第二次則沒有。為了這個第二次呼叫,我們需要「App.xaml」的魔法。

<Application x:Class="WpfTutorialSamples.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             DispatcherUnhandledException="Application_DispatcherUnhandledException"
             StartupUri="WPF Application/ExceptionHandlingSample.xaml">
    <Application.Resources>
    </Application.Resources>
</Application>
using System;
using System.Windows;

namespace WpfTutorialSamples
{
	public partial class App : Application
	{
		private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			MessageBox.Show("An unhandled exception just occurred: " + e.Exception.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Error);
			e.Handled = true;
		}
	}
}

我們處理此例外與區域性之處理方式相當接近,僅在訊息框有非常小的文字以及圖片差異。也請留意我將「e.Handled」屬性設定為「true」,這將告知WPF我們已處理完此例外且沒有其他相關事項需完成。

總結

例外處理是應用程式非常重要的一個部分,而幸運地WPF及.NET使不論區域或全域的例外處理都變得非常容易。由於區域性例外處理允許你更精確且透過更專門的方式處理問題,你應該在合理的狀況下採用區域性例外處理,並且只使用全域性例外處理作為最後防線機制。


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!