I'm trying to implement an uncaught exception handler in an Android only app built with Xamarin for logging purposes.
AppDomain.CurrentDomain.UnhandledException += (o, e) => exLogger.UncaughtException((Exception)e.ExceptionObject);
TaskScheduler.UnobservedTaskException += (o, e) => exLogger.UncaughtException(e.Exception);
and
public void UncaughtException(Exception ex)
{
try
{
Log.Error(TAG, "Exception caught: {0}", ex.Message ?? "Unknown Exception");
var di = Directory.CreateDirectory(Path.Combine(context.FilesDir.AbsolutePath, TAG));
//Rest of Handler - saves error to file system, attempts to upload to a server
...
}
catch (Exception)
{
Log.Error(TAG, "Exception handler failed");
}
}
The handler in question works with zero problems when I implement it in a very simple "Hello World" application, where I trigger an exception on button-press:
throw new Exception("this is a test exception");
(or similar).
However, When I do the same thing in the application I am actually developing, the app crashes inside the handler, printing no further information as to why this happens.
When I step through my code, the debugger hits a breakpoint at the entry to the handler - e.g. within the try block, but before the Log.Error line. However, attempting to step further than this point results in immediate app crash, without either the Log.Debug line in the try OR catch block being executed - nothing is printed to the ADB Logger. Additionally, the error printed to the ADB Log by W/system.err is only the error I intentionally caused (to trigger the handler) - no information on the crash WITHIN the handler is provided.
Does anyone have any idea what could be causing this crash, or even advice on how to get more information from the ADB logs on what the crash within the handler was caused by? My only train of thought is that, because my app is a WebView application, potentially the WebView itself is consuming the Exception in some manner? Any help is greatly appreciated!
Related
Preface I've changed the title. It is hard to understand why, while debugging, sometimes uncaught exceptions print 'FATAL EXCEPTION' to the Logcat and sometimes they don't.
The simplified example below crashes when I get to the line client1.getInputStream(). There is no stack trace or other indication inside of Logcat as to what went wrong. I am running Android Studio 3.0.0beta4.
Why is it crashing? (update - crash was due to a SecurityException)
And why does Logcat not show a stack trace or
other error?
Update
Okay, I figured out why it crashes. I added catch(Exception ex) {...} and found that an exception was in fact being thrown, for I had forgotten to test for it. Stupid error, I didn't include INTERNET permission in the manifest.
So, I would still like to know why I would get no error indication for the unhandle exception. The app just quietly disappears.
Edit One commenter says
In java, unhandled exceptions are not printed
Here is the logcat message when I force an unhandled NullPointerException
FATAL EXCEPTION: Thread-6729
Process: com.example.myapplication, PID: 30824
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.InputStream java.net.URLConnection.getInputStream()' on a null object reference
at com.example.myapplication.MainActivity.GetDataAsyncFromPlaystore(MainActivity.java:79)
at com.example.myapplication.MainActivity$1$1.run(MainActivity.java:42)
at java.lang.Thread.run(Thread.java:818)
So, why not for SecurityException?
Edit2 Just to make things more confusing, I've discovered that when I set a break point prior to the exception point, then step through the code and step over the offending line (the one causing the SecurityException), the App abruptly terminates with with no indication as to why. If however, I hit F9 before reaching the offending line, I do, in fact, get a "FATAL EXCEPTION" message logged in Logcat. (Therefore, I've added back the "android-studio" tag to the question.)
So, same question, slightly different wording: Why does the exception print a 'FATAL EXCEPTION' message when debugging one way, but not the other?
The (simplified) code
public void GetDataFromWebsite()
{
Uri queryUri = Uri.parse("https://play.google.com/store/search?q=Planning&c=apps");
try {
URL queryUrl = new URL(queryUri.toString());
URLConnection client1 = queryUrl.openConnection();
InputStream in = client1.getInputStream();
Log.d("Test", "Okay");
} catch (MalformedURLException muex) {
Log.e("Test", "Malformed Url", muex);
} catch (IOException ioex) {
Log.e("Test", "IO Error", ioex);
// } catch(Exception ex) {
// Log.e("Test","Other Exception", ex);
}
}
NOTE:
You are just catching MalformedURLException and IOException. So you won't get other exceptions.
Catch with Exception you will get a trace.
UnHandled exception not printed in android log cat. you can print UnHandled exception by UncaughtExceptionHandler. Here is a like to implement UncaughtExceptionHandler: Logging unhandled exceptions in Android Activity
There is no relativity between NullpointerException and SecurityException. How it will get caught by SecurityException.
I have made an application that send and receive data via socket it works in Android os < 7.0.0 but when i launche this application in android nougat(7.0.0) it display an error when receiving replay it display android.os.NetworkOnMainThreadException error at lign (dataOutputStream.writeUTF(msgReply);) so how can i fix this error thanks for yours attention.
Code:
String msgReply = "&sim1$extr€"+getIpAddressonly()+"?8080.wifi/";
try
{
dataOutputStream.writeUTF(msgReply); // error at this line
}
catch (IOException e) {
e.printStackTrace();
}
You need to get your network I/O off the main (UI) thread. Start a background thread to do network I/O.
We usually initialize Crashlytics in the very early stage in our Application.onCreate() method in main thread. The initialization process of Crashlytics is usually very fast, but it could still take more than 2 frames and as long as 32ms on some devices. Since we are constantly improving our cold start time, we thought about putting the Crashlytics initialization into a background thread and the concern is whether we can still capture a crash before the Crashlytics is initialized.
Our approach here is to set up a CustomDefaultUncaughtExceptionHandler as the first thing and initialize Crashlyatics really early as well but in a background thread. If we got a crash before the Crashlytics is initialized or to be initialized, we will reinitialize Crashlytics in the CustomDefaultUncaughtExceptionHandler and use reflection to get CrashlyticsCore's CrashlyticsUncaughtExceptionHandler and then log this uncaught exception.
Our ask is whether it's possible to make a public method for us to log a uncaught exception so that we don't have to use reflection. Or if there are some other suggestions for us to offload the Crashlytics initialization to a background thread but also be able to catch early exceptions.
The pseudo code looks like the following:
public void uncaughtException(Thread thread, Throwable ex) {
try {
if (_crashlyticsEnabled) {
if (!_crashlyticsInitialized) {
// IMPORTANT: in case we encounter a crash before the crashlytics is
// initialized, we can initialize crashlytics here and send this crash
// to the server right away.
initCrashlytics(_context);
Crashlytics.logUncaughtException(thread, ex); // API we are asking
}
}
} catch (Exception e) {
PLog.error(e, "Exception occurred during ...");
} finally {
_defaultExceptionHandler.uncaughtException(thread, ex);
}
}
I'm working on an application with Xamarin (in Visual studio 2015) for android.
When I run my application in debug mode, sometime the application stop with message "MyApplication has stopped".
I've added this code in MainActivity :
// Catch Exception
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
I added breakpoints add log in both functions, but I see no traces in log and the breakpoints are not reached.
How can I debug this kind of problem ?
You need to debug your application through a persistent logger i.e. adb logcat. Sadly registering an unhandled exception handler does not guarantee it will be a "catch-all" as it might never reach that point. So you will need a combination of both adb logcat and Console.WriteLine for these types of issues. Please take the following note into account when you want to see what's going on within this handler, but also make use of adb logcat to see the reason of the crash in the first place.
/// <summary>
/// When app-wide unhandled exceptions are hit, this will handle them. Be aware however, that typically
/// android will be destroying the process, so there's not a lot you can do on the android side of things,
/// but your xamarin code should still be able to work. so if you have a custom err logging manager or
/// something, you can call that here. You _won't_ be able to call Android.Util.Log, because Dalvik
/// will destroy the java side of the process.
/// </summary>
protected void HandleUnhandledException (object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception) args.ExceptionObject;
// log won't be available, because dalvik is destroying the process
//Log.Debug (logTag, "MyHandler caught : " + e.Message);
// instead, your err handling code shoudl be run:
Console.WriteLine ("========= MyHandler caught : " + e.Message);
}
https://github.com/xamarin/monodroid-samples/blob/fb9d4ed266bdf68bb1f9fa9933130b285712ec82/AdvancedAppLifecycleDemos/HandlingCrashes/App.cs
Try it: Disabled "Use Shared Runtime" in Android build options. If it not helped try - disable "Use fast deplayment".
I have been working with Eclipse/Android development porting a game from windows for about a month now.
But I have been frustrated with some aspects of this Environment.
When I get an exception, very rarely does the debugger stop where it needs to.
I have tried adding Exception breakpoints, this helps hit a few errors in relevant code but still very hit and miss.
Visual studio always stops execution in the closest entry point to the throwing of the exception, and I really miss that.
Even a minor
myArrayList[outOfBounds]
does not stop on the line that caused the issue.
I would like to know what experienced android developers do to track down the cause of exceptions quickly.
Put a try{ block around the statements that are going to generate the exception and then in the catch do something like
catch (Exception e) {
System.out.println("Test \"" + arg +
"\" threw a " + e.getClass() +
"\n with message: " + e.getMessage());
}
You can use try - catch block. Whenever any exception comes your catch block will be executed so you can put alert or message in catch block to track your problem or you can use Exception parent class to trace your bug.
try{
Your code to execute
}catch(Exception e){
e.printStackTrace();
}
This will give you error log in your logcat.