In short, MSDN describes exception dispatching for user mode application like this:
the debugger gets notified of the first chance exception (if attached)
an exception handler aka. try/catch is invoked (if available)
the debugger gets notified of the second chance exception (if attached)
the system cares about the unhandled exception (typically: terminate the process)
This sequence does not consider the presence of an unhandled exception handler. How does exception dispatching change when an unhandled exception handler is present?
The unhandled exception handlers insert at position 3. The sequence is:
the debugger gets notified of the first chance exception (if attached)
an exception handler aka. try/catch is invoked (if available)
the unhandled exception handlers (note the plural) are called (if available)
the debugger gets notified of the second chance exception (if attached)
the system cares about the unhandled exception (typically: terminate the process)
The following C# program demonstrates it. Depending on the .NET version, you'll a message of another unhandled exception handler, which is the .NET framework printing the exception and the call stack.
using System;
namespace UnhandledException
{
static class Program
{
static void Main()
{
Console.WriteLine("Please attach the debugger now and press Enter.");
Console.ReadLine();
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Unhandled1();
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Unhandled2();
try
{
Console.WriteLine("Throwing now.");
// Will cause a first chance, because in try/catch
throw new Exception("Any exception will do");
}
catch (Exception)
{
// Will cause first chance and second chance, because in NOT try/catch
Console.WriteLine("In catch block.");
throw;
}
}
static void Unhandled1() => Console.WriteLine("In unhandled exception handler 1");
static void Unhandled2() => Console.WriteLine("In unhandled exception handler 2");
}
}
Commands required in the debugger (WinDbg):
.symfix
.reload
sxe clr
g; *** for the breakpoint due to attaching the debugger
g; *** first chance in try/catch
g; *** first chance outside try/catch
g; *** second chance
Related
This link describes how to handle exceptions in iOS
Runtime.MarshalManagedException += (object sender, MarshalManagedExceptionEventArgs args) =>
{
Console.WriteLine ("Marshaling managed exception");
Console.WriteLine (" Exception: {0}", args.Exception);
Console.WriteLine (" Mode: {0}", args.ExceptionMode);
};
Runtime.MarshalObjectiveCException += (object sender, MarshalObjectiveCExceptionEventArgs args) =>
{
Console.WriteLine ("Marshaling Objective-C exception");
Console.WriteLine (" Exception: {0}", args.Exception);
Console.WriteLine (" Mode: {0}", args.ExceptionMode);
};
In addition, I've seen other Xamarin samples use this in the AppDelegate
AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
try
{
var exception = ((Exception)e.ExceptionObject).GetBaseException();
Console.WriteLine("**SPORT UNHANDLED EXCEPTION**\n\n" + exception);
exception.Track();
}
catch
{
throw;
}
};
Question
What are the exception types (if more than Managed/Unmanaged), and how do I capture everything?
It goes without saying that a 'global' exception handler should not be a replacement for correctly catching expected or anticipated exceptions from blocks of code you anticipate to see issues with (perhaps because you use the parrallel libaries, or anything with any kind of thread complexity).
'global' exception handlers (in my opinion) should be used to catch anything you've failed to spot during development and testing. Personally I write these to a log file in our applications and handle them as 'Critical Exceptions' as they will cause the application to crash. My preferred method is to assign an event to 'AppDomain.CurrentDomain.UnhandledException'.
That being said during development, testing and if during production the users of your application happen to have 'diagnostic reporting' set to on you will be able to access apples exception logs. These can be useful but bear in mind they will give you the 'native' stack trace and won't have anything specific to xamarin in them. So take them with a pinch of salt.
as to your question, assigning to 'AppDomain.CurrentDomain.UnhandledException' will capture every exception that you haven't done or forseen yourself. you don't need to know the types explicitly as the stack trace will obviously tell you what they are. it's also worth noting that you can only use that event to record information or perform very basic functions as the app will close irrespective of what you do. So use it to log as much information regarding your application as possible.
It is currently impossible to stop your application from closing if it hits the unhandledexception event.
I have an IdHTTP component and when I get a HTTP error (for example 404) Indy shows a message box. I want to handle this "silent" and prevent Indy from showing this.
I have not found any parameter to turn this off. Any ideas?
Indy does not display message boxes. It throws exceptions. There are default exception handlers inside the VCL/FMX framework that will display a message box to the user if an exception is not caught in your code. So simply catch the exception in your code, eg:
try
{
IdHTTP1->Get(...);
}
catch (const Exception &)
{
// do something...
}
If you need finer control over the exception filtering, all Indy-specific exceptions are derived from EIdException, and there are many descendants (like EIdHTTPProtocolException), eg:
try
{
IdHTTP1->Get(...);
}
catch (const EIdHTTPProtocolException &)
{
// an HTTP error occured, do something...
// details about the HTTP error are in the exception object
}
catch (const EIdException &)
{
// a non-HTTP Indy error occured, do something else...
}
catch (const Exception &)
{
// some other error occured, do something else...
}
I have MS Test unit tests that ensure that an Exception is thrown when the method under test is given bad arguments. I'm using the pattern:
My actual;
bool threw = false;
try
{
actual = target.DoSomething(aBadParameter);
}
catch
{
threw = true;
}
Assert.IsTrue(threw);
I have CLR Exceptions set to break only when user-unhandled (not when thrown). When DoSomething() throws a new Exception(), however, the debugger breaks. If I resume, the unit test completes successfully.
If I cut-and-paste the unit test code into the main program and run it in the context of the main program (instead of under MS Test), the debugger does not break at the user-handled Exception.
How can I prevent the debugger from breaking on my user-handled Exceptions?
This does not appear on the surface related to
Getting an Unhandled Exception in VS2010 debugger even though the exception IS handled
because in that case the Exception was being thrown on a different thread and was being rethrown by the CLR inside a callback.
The idiomatic way to test for thrown exceptions in MSTest is using the ExpectedException attribute:
[TestMethod]
[ExpectedException(typeof(FooException))]
public void ThrowsFooExceptionWithBadInput()
{
var actual = target.DoSomething(aBadParameter);
}
I need to generate code at runtime that do the following:
auto v_cleanup = std::shared_ptr<void>(nullptr, [](void *){ cleanup(); });
//...
do_some_danger_thing();
//...
or C equivalent:
__try {
//...
do_some_danger_thing();
//...
} __finally {
cleanup();
}
The cleanup() function is guaranteed to be exception free, however do_some_danger_thing() may throw exception. This runtime code MUST not use stack, which means when calling do_some_danger_thing() the stack must in the same status as when we enter the runtime code, except that the return address set to the runtime code (the original value was saved to a "jmp" target, in order to return to the caller).
Because we are using dynamic machine code, the target platform is fixed to WIN32 on x86 CPU, the x64 CPU is not currently in focus.
To do this we have to process any exceptions. In WIN32 C++ exception is SEH based, so we have to due with it. The trouble is that we cannot find a way to do this and make it compatible with other code. We have tried a couple of solutions but none of them works, sometimes the user-installed exception handler was never called, sometimes the outer exception handlers was bypassed and we received an "unhandled exception" error.
UPDATE:
It seems to be the case that SEH exception handler chain supports code within the EXE image only. If the exception handler pointed to my generated code it will never been called. What I have to do is to create a static exception handler function stub, and then let it call the generated handler.
I am now have an implementation that is slightly different with the above. Actually, the pseudo code looks like (in C++11):
std::exception_ptr ex;
try {
//...
do_some_danger_things();
//...
} catch (...) {
ex = std::current_exception();
}
cleanup();
if(ex)rethrow_exception(ex);
This is not 100% the same as the above C equivalent because the call of cleanup() occurs before stack unwinding, usually this is not a problem, but the exact exception context could be lost.
I implemented an internal exception handler as the helper function, like the following:
_declspec(thread) void *real_handler = nullptr;
void **get_real_handler_addr(){
return &real_handler;
}
__declspec(naked) int exception_handler(...){
__asm {
call get_real_handler_addr;
mov eax, [eax];
jmp eax;
}
}
The trick here is that this handler must not be generated at runtime, so the stub has to find out where the "real" handler is. We use a thread local storage to do this.
Now the generated code will get the exception handler chain from FS:[0]. However, the chain must be stack based so I use the following code to replace the handler:
void **exception_chain;
__asm {
mov eax, fs:[0]
mov exception_chain, eax
}
//...
void *saved_handler = exception_chain[1];
exception_chain[1] = exception_handler;
*get_real_handler_addr() = generated_code->get_exception_handler();
The generated exception handler can then do the cleanup. However, in case that any current exception handler returns EXCEPTION_CONTINUE_SEARCH, the handler will be called twice. My strategy is just restore the original exception handler within the first call.
I have an issue with VS2010 where the debugger stops with an Unhandled Exception. However, the exception is definitely handled. In fact, if I put code in the catch block, I'll hit it when I press F5. In Debug -> Exceptions, I definitely do not have the "Thrown" checkbox checked, so IMO there is absolutely no reason for the unhandled exception dialog to pop up...
I can't post the exact code, but will work on a sample soon. The basic idea behind the offending code section is that I have a thread that talks to hardware, and if I have an error talking to it, then I throw a HardwareException. The thread is launched with BeginInvoke, and the exception is caught in the callback handler when I call EndInvoke.
When the exception is thrown in the debugger, I get a messagebox that says 'HardwareException not handled by user code". But it is!!!
EDIT -- Well, this is driving me crazy. I've got sample code that is representative of the code I have in my application, and it looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Threading;
namespace ConsoleApplication1
{
public class HardwareException : ApplicationException
{
public HardwareException( string message) : base(message) {}
}
class Program
{
delegate void HardwareTestDelegate();
static void Main(string[] args)
{
HardwareTestDelegate d = new HardwareTestDelegate( HardwareTestThread);
d.BeginInvoke( HardwareTestComplete, null);
while( true);
}
static void HardwareTestThread()
{
throw new HardwareException( "this is a test");
}
static void HardwareTestComplete( IAsyncResult iar)
{
try {
AsyncResult ar = (AsyncResult)iar;
HardwareTestDelegate caller = (HardwareTestDelegate)ar.AsyncDelegate;
caller.EndInvoke( iar);
} catch( Exception ex) {
Console.WriteLine( "Should see this line without getting an unhandled exception message in the IDE");
}
}
}
}
I throw my HardwareException from the thread, and then handle the exception when EndInvoke is called. I guess Murphy was right, because when I run this sample code, it does what I expect -- i.e. no unhandled exception error message pops up in the IDE!
Here is the response from Microsoft, case 111053102422121. Allen Weng writes the following:
Analysis:
For your information, CLR will re-throw the exception inside the callback when you call EndInvoke(). Below is a simplified version of EndInvoke():
public object EndInvoke(IAsyncResult asyncResult)
{
using (new MultithreadSafeCallScope())
{
ThreadMethodEntry entry = asyncResult as ThreadMethodEntry;
............
if (entry.exception != null)
{
throw entry.exception;
}
}
}
The exception will be handled in the call back function or in the asynchronous method if an exception handler is provided. This is how it works without a debugger attached.
When you run it in VS.NET, the debugger seems checking only the presence of the exception handler in the asynchronous method. If there is no such handler, the debugger would think the exception is not handled and pop up an error message notifying you of this.
Suggestion:
The application should work as expected when you run it stand alone. If the error message is annoying in debugging for you, you can disable it by unchecking “User unhandled” for “Common Language Runtime Exceptions”in the Exception dialog box (Debug|Exceptions or press CTRL+ATL+E). Or you can add try/catch in the asynchronous method. In the latter case, the exception is set to null and won’t be re-thrown in EndInvoke().
I'm having this same problem, so I'll post this possible workaround for posterity's sake:
In your code that throws an exception into the .NET code (HardwareTestThread() in the example above,) catch the exception that's being thrown and wrap it in some esoteric .NET exception type for which you can disable the "user-unhandled" option in the Debug>Exceptions dialog. For my case, I needed to allow an IOException to propagate through some .NET code back to my code, so I just caught the IOException and wrapped in an AppDomainUnloadedException before letting it propagate through the .NET code back to my catch block. I chose AppDomainUnloadedException because user-unhandled is unchecked for it by default and it's in the System.dll assembly, so it was already being imported in my project, though any exception should work, so long as you disable the "user-unhandled" option for it and you don't care that the debugger won't break on that type of exception in the future.
Here's my code that wraps the IOException I was needing to propagate:
public override int Read(byte[] buffer, int offset, int count)
{
try { return innerStream.Read(buffer, offset, count); }
catch (IOException ex) { throw new AppDomainUnloadedException("Exception from innerStream: " + ex.Message, ex); }
}
And here's my code where I'm catching it on the other side of the .NET code it needed to propagate through:
try { bytesRead = sslStream.Read(buffer, offset, count); }
catch (Exception ex) { /* ex handled here. */ }