Xamarin按钮单击处理异常

时间:2014-11-07 04:05:09

标签: c# .net xamarin

我第一次与Xamarin合作,并且仍在掌握一些基础知识。

请参阅下面的示例

    protected override void OnCreate(Bundle bundle)
    {
        try
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Login);

            Button button = FindViewById<Button>(Resource.Id.Login);

            button.Click += delegate
            {
                   throw new Exception("button exception");
            };
        }
        catch(Exception e)
        {
        }
}

我已经简化了上面的代码,直截了当。

我正在为我的活动内部设置一些通用的错误处理,作为一个例子,我在点击按钮时抛出异常。尽管这被包装在try / catch中,但异常被抛出为“未处理的异常”。

希望有人能解释这段代码是如何在逻辑上运行的,我假设它是某种线程问题?我怎样才能最好地处理这种情况?

最终目标是我想要进行一些内部调用来登录;返回任何错误消息,然后用消息框将其冒泡。不幸的是,我似乎无法捕获它们。

感谢。

我尝试使用以下代码设置一个全局处理程序:

   protected override void OnCreate(Bundle bundle)
    {
        try
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Login);

            Button button = FindViewById<Button>(Resource.Id.Login);
            string accountCode = Resource.Id.AccountCode.ToString();
            string password = Resource.Id.Password.ToString();

            button.Click += delegate
            {
                 throw new Exception("Invalid account code or password. Please try again.");
            };
        }
        catch(Exception e)
        {
        }
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
    {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();

        throw new Exception("AH HA!");
    }

2 个答案:

答案 0 :(得分:4)

这样的事情应该有效:

button.Click += (sender, event) =>
{
    try
    {
       throw new Exception("button exception");
    }
    catch(Exception ex)
    {
    }
};

基本上,try / catch在委托中(我已将其更改为lambda)。如果您要进行长时间运行,请考虑将其设置为异步/等待兼容:

button.Click += async (sender, event) =>
{
    try
    {
       throw new Exception("button exception");
    }
    catch(Exception ex)
    {
    }
};

答案 1 :(得分:1)

这是因为您的catch仅限于OnCreate方法,它将捕获此方法内部抛出的异常。你的点击处理程序是在OnCreate方法之外调用的,因此你的catch在那里不起作用。

作为可能的解决方案,请查看此处:.NET Global exception handler in console application