0

In my MonoDroid application, when an unhandled exception occurs the application terminates without any messages. If I can reproduce the error on my local device I can debug it through Visual Studio without any problems.

However, on remote devices I am stuck for a solution.

I have tried the following in the Application class but it does not actually write my log file, unless I am running through the debugger in Visual Studio.

public override void OnCreate()
    {
        base.OnCreate();                                    
        AndroidEnvironment.UnhandledExceptionRaiser += new EventHandler<RaiseThrowableEventArgs>(AndroidEnvironment_UnhandledExceptionRaiser);
    }

    void AndroidEnvironment_UnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
    {
        // Write Log File
    }
Trevor
  • 2,186
  • 3
  • 16
  • 18
  • Can you mark my answer as the correct one? @SpiritMachine admitted that his answer doesn't work. – Jim G. Jun 26 '13 at 11:03

2 Answers2

3

I disagree with @SpiritMachine's answer.

Mono documentation tells us:

Note: You cannot rely on the AppDomain.UnhandledException event as managed exceptions are never unhandled in MonoDroid; they are always intercepted at the Android/managed boundary within a catch(Exception) block.

Instead, I recommend that you do the following:

AndroidEnvironment.UnhandledExceptionRaiser += (sender, args) =>
{
    // Do something...
};
Community
  • 1
  • 1
Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • Care to elaborate? I believe `AppDomain.CurrentDomain.UnhandledException` will also work on Monotouch and WP, making it a cross platform solution. – manadart Jun 11 '13 at 07:20
  • Fair enough. It does actually catch the error; you just can't do anything with it - even just logging throws again. I can't delete the answer because it's accepted, but the advice there holds - handle locally. – manadart Jun 26 '13 at 08:23
  • "Handle Locally" -- I'm not sure how to interpret that except that every user action (button click, etc) needs its own try/catch. I'm new to Xamarin, but in every other .net situation (web, winform, etc) there's a decent way to at least say, "Something unexpected and bad has happened; here's an exception message and a stack track to give to a developer" (or some such thing). Is there no such mechanism in android/xamarin? – pettys Dec 16 '13 at 22:11
  • @pettys: Yes, there is. Follow my advice. Ignore SpiritMachine's. He was just being stubborn. – Jim G. Dec 16 '13 at 22:46
-1

Try something like this:

EDIT : This code cannot handle caught errors. Please see @Jim G.'s answer....

Personally, I would localise error handling to where you need it. The reason being, you don't know what your application state will be when this handler is recruited - you may be without resources that you're depending on to do the handling...

Community
  • 1
  • 1
manadart
  • 1,750
  • 11
  • 13