我正在爲Windows Phone 8.1(Silverlight)開發C#應用程序。最近我遇到了與應用程序入睡和故事板有關的問題。Catch不執行其代碼
構造變爲如下:
class X : DependencyObject
{
public static readonly DependencyProperty vProperty =
DependencyProperty.Register("v", typeof(double), typeof(X), new PropertyMetadata(0.0));
public double v
{
get
{
return (double)GetValue(vProperty);
}
set
{
SetValue(vProperty, value);
}
}
private Storyboard _storyboard;
void Prepare()
{
_storyboard = new Storyboard();
var animation= new DoubleAnimation
{
From = 0,
To = 1,
BeginTime = 0,
Duration = 0,
};
_storyboard.Children.Add(animation);
Storyboard.SetTarget(animation, this);
Storyboard.SetTargetProperty(animation, vProperty);
}
void Go()
{
_storyboard.Begin();
}
}
有從_storyboard.Begin()的內部拋出一個NullReferenceException如果應用設備被置於背景「準備」和「去」(約10%的再現速率之間)。當然,它最終會崩潰。
我無法確定問題的來源,因爲我需要quickfix,因此我決定在這種罕見的情況下發現這個NullRefereneceException。這是真正的問題開始的地方。我已經改變了「去」實施:
public void Go()
{
Debug.WriteLine("BreakPoint 1");
try
{
_storyboard.Begin();
}
catch (NullReferenceException)
{
Debug.WriteLine("BreakPoint 2");
}
}
之後崩潰是不可複製的所有,但問題是,「斷點2」從不打(在輸出中沒有打印其一)。 「BreakPoint 1」通常也會被打印和打印。將NullReferenceException更改爲其他異常類型(不是父類型的c)會導致崩潰重新出現。
那麼......這裏發生了什麼事?這崩潰緩存或不?這是什麼奇怪的行爲?假設它能按預期工作是否安全?
附加問題:也許你知道爲什麼原始代碼崩潰的第一個地方?
編輯: 結束TargetInvocationExceptions的internalException的堆棧跟蹤看起來如下:
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.Storyboard_Begin(Storyboard storyboard)
at System.Windows.Media.Animation.Storyboard.Begin()
at X.Go()
那麼程序仍然崩潰或沒有?如果你有它捕獲一個通用的'例外'會發生什麼? – user1666620
它沒有崩潰,但它看起來像捕獲內的代碼不會執行。任何NullRefrenceException父類的異常類型都會修復崩潰。任何其他異常類型都不能修復崩潰。 – Yester
如果你得到一個'TargetInvocationException',那麼這就是你需要捕獲的。 'InnerException'屬性可能是你的'NullReferenceException',但你不能理解(除非你使用C#6.0,你可以這樣做:'catch(TargetInvocationException ex)when(ex.InnerException是NullReferenceException)') 。 –