Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
[docs] Document Exception Handling semantics #4877
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
[docs] Document Exception Handling semantics #4877
Changes from all commits
49fdc42File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
There are no files selected for viewing
Exception Handling
Outside of Xamarin.Android, .NET exception handling when a debugger is attached potentially involves walking the runtime stack twice, involving three interactions between the runtime and the debugger:
When the exception is first thrown, a first chance notification is raised in the debugger, which provides the debugger with an opportunity to handle breakpoint or single-step exceptions.
If the debugger doesn't handle or continues execution from the first chance notification, then:
a. The runtime will attempt to "find a frame-based exception handler that handles the exception".
b. If no frame-based exception handler is found, then a last-chance notification is raised in the debugger.
If the debugger doesn't handle the last chance notification, then execution will continue, causing the stack to be unwound.
The first stack walk is step 2(a), while the second stack walk is step (3).
Within Xamarin.Android, if a thread call-stack doesn't involve any calls to or from Java code, the same semantics are present.
When a thread call-stack involves calls to or from Java code, the above "two-pass" semantics cannot be supported, as the Java Native Interface, which is used to support calls to or from Java code, does not support them. A cross-VM runtime stack can only be walked while being unwound; there is no way to ask "is there any method which will handle this exception" before code is executed and the stack is unwound.
The Setup
Consider the following Java code:
Demo.run()is bound as:Now imagine the above Java class has been bound and is used from a Xamarin.Android app:
Exception Handling Without A Debugger
When a debugger is not attached, the following happens:
Java.Lang.Runnablehas a Java Callable Wrapper generated at app build time,mono.java.lang.Runnable, which implements thejava.lang.RunnableJava interface type.When the
Java.Lang.Runnableis created, amono.java.lang.Runnableinstance is also created, and the two instances are associated with each other.The
Demo.Run()invocation invokes the JavaDemo.run()method, passing along themono.java.lang.Runnableinstance created in (2).The
r.run()invocation withinDemo.run()eventually invokes the methodJava.Lang.IRunnableInvoker.n_Run():However, invocation of
n_Run()is wrapped in a runtime-generatedtry/catchblock, which is equivalent to:This runtime-generated
try/catchblock is used for every Java-to-managed call boundary; the method invoked in thetryblock changes.AndroidEnvironment.UnhandledException()is responsible for calling theJNIEnv::Throw()JNI method.At this point in time, the runtime call-stack is:
Demo.run()method, which calls >try/catchblock, which calls >IRunnableInvoker.n_Run()method, which calls >Actiondelegate.The
Actiondelegate is invoked, causing a C# exception to be thrown.The exception thrown in (7) is caught by the method in (5). The managed exception type is wrapped into a
JavaProxyThrowableinstance, which is then raised in the Java code.The Java
finallyblock executes, and then theDemo.run()method is unwound by the JVM.The
Demo.Run()binding sees the "pending exception" from the JNI call, "unwraps" theJavaProxyThrowableto obtain the originalSystem.Exceptionthen raises theSystem.Exception.If the method calling
Demo.Run()was invoked from Java code, e.g. anActivity.OnCreate()method override contained the sample code, then the runtime-generatedtry/catchblock will catch the exception being propagated from (10) and likewise wrap it into aJavaProxyThrowable.The Java stack frames will unwind, and the Java uncaught exception behavior kicks in:
java.lang.Thread.getUncaughtExceptionHandler()andjava.lang.Thread.UncaughtExceptionHandler.uncaughtException()are invoked.During process startup, Xamarin.Android inserts itself into Java's uncaught exception handler chain. As such,
JNIEnv.PropagateUncaughtException()is invoked, which will attempt to invokeDebugger.Mono_UnhandledException(), which gives an attached debugger a chance to observe the exception, andAppDomain.DoUnhandledException()is invoked, which will raise theAppDomain.UnhandledExceptionevent, giving managed code a chance to deal with the pending unhandled exception.The process exits, because the
System.Exceptionisn't handled. :-)Exception Handling With A Debugger
When the debugger is attached, runtime behavior differs significantly. Steps (1) through (4) are the same, then:
Invocation of
n_Run()is wrapped in a runtime-generatedtry/catchblock which pulls in the debugger via an exception filter, and is equivalent to:The runtime call-stack is unchanged relative to execution without a debugger.
The
Actiondelegate is invoked, causing a C# exception to be thrown.No first chance notification is raised. Instead, Mono will "find a frame-based exception handler that handles the exception," and as part of this process will execute any exception filters. This causes
Debugger.Mono_UnhandledException()to be executed, which is what triggers the "System.Exception has been thrown" message within the debugger.If you look at the Call Stack Debug pad within Visual Studio for Mac,
System.Diagnostics.Debugger.Mono_UnhandledException_internal()andSystem.Diagnostics.Debugger.Mono_UnhandledException()are the topmost call stack entries.The Java
finallyblock withinDemo.run()has not executed yet.If
Demo.run()had acatch(Throwable)block instead of afinallyblock, it likewise (1) would not have executed yet, and (2) will not participate in the stack walking to determine whether or not the exception is handled or unhandled in the first place.The exception is not yet "pending" in Java either, so it is safe to invoke Java code in e.g. the Immediate window.
If execution is continued, e.g. via Continue Debugging, then
AndroidEnvironment.UnhandledException()will be executed, causing the exception to be wrapped and become a "pending exception" within Java code. After this point, any invocation of Java code from the debugger will immediately cause the process to abort:Furthermore, No Java code can ever again execute within the process. Once execution is continued, Mono will be unwinding the call stack without involvement of the Java VM.
The
finallyblock withinDebug.run()hasn't executed yet, and will never execute. In particular, theSystem.out.println()message isn't visible inadb logcat!If
Debug.run()instead had acatchblock, it will similarly never be executed.Execution then "breaks" at the managed
Debug.Run()method. At this point there is a pending exception within Java; any invocations of Java code from the debugger will immediately cause the process to abort.If execution is continued again, the process will exit.
Unexpectedly (2020-06-26), the exit is also due to a JNI error:
Internal context: