c#异常汇总(持续更新中)

1.System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.(英文翻译:目标调用异常)

解答:出现的原因是,交付给别的线程的时候,别的线程没法反射到相应的地方。发生这种异常比较普遍,这里只拿一个例子说明,

比如,info.count()==0,有可能info.count()为null,此时作比较就有可能报这个错误。

2.“System.UnauthorizedAccessException”类型的未经处理的异常在 System.Windows.ni.dll 中发生

解答:有可能没有用dispatcher交付UI线程。

特别注意:有的时候为了抓异常,我们用了try.. catch{ messagebox.show(xx);},但是界面已经不在这里了(比如后台任务),恰好崩溃掉。

Dispatcher.BeginInvoke(
                            () =>
                            {
                            //我的代码
                            });
dispatcher UI交付

3.页面的宿主用来管理导航的 NavigationService 对象;如果宿主不支持导航,则为 null(msdn)。

解答:当,只是引用另一个页面中的类的方法,却未重载此页面的时候,导航是不可用的,解决方案如下。

private static PhoneApplicationFrame _frame;

      public static PhoneApplicationFrame Frame
      {
          get { return _frame ?? (_frame = (PhoneApplicationFrame) Application.Current.RootVisual); }
      }
//调用
      private void useframe() { PublicMethod.Frame.Navigate(new Uri("xxx", UriKind.Relative)); }
万能导航

4.Value does not fall within the expected range?

解答:listbox下拉刷新的时候遇到此问题,

解决方式:After you clear can just for the sake of debugging ensure that the list of items is empty. Maybe you should consider putting the clear within the callback.

(参考自stackoverflow:http://stackoverflow.com/questions/10284992/value-does-not-fall-within-the-expected-range)

先前以为是使用的httpclient有问题,后来根据追踪的debug错误信息,方式如下:

 

 private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // 出现未处理的异常;强行进入调试器
                MessageBox.Show(e.ExceptionObject.Message);
                Debugger.Break();
            }
        }
debugger追踪

 

才知道是listbox清空值太早(listbox.clear())导致的,

即:下拉->clear->loadmore->ToNewContainer(报错)。

现在改为:下拉->loadmore->clear->ToNewContainer(成功)。

5.Object reference not set to an instance of an object.

解答:这种异常也很常见,我的理解是,当对象还没有被创建的时候,就赋给了示例。这次遇到的场景是:

使用winphone8的longlistselector方法:MyLls.ScrollTo(mylist.FirstOrDefault());

联网没问题,可能因为直接从本地读取信息的速度》》网络拉取速度。导致MyLls的第一项没加载出来,解决方法是:

  Dispatcher.BeginInvoke(()=>MyLls.ScrollTo(mylist.FirstOrDefault())) ;

交付给别的线程就可以了。但是异步调用的话有延迟卡,建议直接try catch掉断网,用同步。

posted on 2014-09-26 10:11  鸣动我心  阅读(924)  评论(0编辑  收藏  举报