有没有办法处理无法访问的异​​常?

Gab*_*abe 2 c# silverlight exception

在Silverlight 4应用程序中,我在包含的控件(DataGrid)上调用一个函数,此函数有时会抛出类型的虚假异常MS.Internal.WrappedException.由于这个例外没有意义,我需要吞下它.不幸的是,异常是internal class WrappedException : Exception在System.Windows.dll中声明的,所以我无法在一个catch块中命名.

问题是,检测此异常并忽略它的最安全的方法是什么?我提出的两个选项是:

  1. 寻找原始异常: ex.InnerException is InvalidOperationException
  2. 寻找名称: ex.GetType().FullName == "MS.Internal.WrappedException"

有一种方式比另一种更好吗?还有其他我没想过的选择吗?

这是我的功能,显示了不同的选项:

    private void SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var selectedAlarm = alarmList.SelectedItem as Alarm;
        if (selectedAlarm != null)
        {
            dataGrid.SelectedItem = selectedAlarm.Source;
            try
            {
                dataGrid.ScrollIntoView(dataGrid.SelectedItem, null);
            }
            // catch (MS.Internal.WrappedException ex) doesn't compile
            catch (Exception ex)
            {
                if (ex.InnerException is InvalidOperationException) // 1
                if (ex.GetType().FullName == "MS.Internal.WrappedException") // 2
                {
                    // ignore exception
                }
                else
                    throw;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

对于那些感兴趣的人,这里是StackTrace:

   at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
   at MS.Internal.XcpImports.UIElement_Measure(UIElement element, Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.DataGrid.InsertDisplayedElement(Int32 slot, UIElement element, Boolean wasNewlyAdded, Boolean updateSlotInformation)
   at System.Windows.Controls.DataGrid.InsertDisplayedElement(Int32 slot, Boolean updateSlotInformation)
   at System.Windows.Controls.DataGrid.GetExactSlotElementHeight(Int32 slot)
   at System.Windows.Controls.DataGrid.ScrollSlotIntoView(Int32 slot, Boolean scrolledHorizontally)
   at System.Windows.Controls.DataGrid.ScrollSlotIntoView(Int32 columnIndex, Int32 slot, Boolean forCurrentCellChange, Boolean forceHorizontalScroll)
   at System.Windows.Controls.DataGrid.ScrollIntoView(Object item, DataGridColumn column)
   at DtDemo.Home.alarmList_SelectionChanged(Object sender, SelectionChangedEventArgs e)

这里是InnerException.StackTrace:

   at System.Windows.Controls.DataGridRow.get_ActualDetailsVisibility()
   at System.Windows.Controls.DataGridRow.OnApplyTemplate()
   at System.Windows.FrameworkElement.OnApplyTemplate(IntPtr nativeTarget)

Han*_*ant 6

这是故意的,所以你不要试图捕捉这个例外.这是一个严重的之一,它是没有意义,也不能忽略它.解决真正的问题.没有堆栈跟踪我无法帮助您诊断原因.