简体   繁体   中英

Can't Catch NetworkOnMainThreadException

I know what causes a NetworkOnMainThreadException, as well as how to fix it, but for the purposes of improving the development experience, I'd like to be able to catch the exception and at least log the event or alert the user (who is still the developer at this point)...

Strangely, I'm not having any luck with this code (which sends and receives over my TCP socket):

try
{
    toServer.println (msg.trim());
    resp = fromServer.readLine();
}
catch (android.os.NetworkOnMainThreadException nex)
{ ... do something here ... }

Eclipse doesn't recognize that exception at all, and I copy-pasta-ed the exception type from the Android Developer website -- I'm pretty sure I spelled it right...

Is there something I don't know about Java (perhaps) that makes this exception uncatchable??

Thanks, R.

Is there something I don't know about Java (perhaps) that makes this exception uncatchable??

Yes, StrictMode makes it uncatchable. Either way though, you should not catch this exception. Instead, you should implement your code correctly by wrapping your code in an AsyncTask . The reason why this exception is thrown is to prevent you from slowing down your application by blocking the UI thread.

Read my blog post for more info:

Why Ice Cream Sandwich Crashes Your App

Well I just tested this on my version of eclipse, and it works just fine.. I guess I would check which version of the api you are using? looks like to throw that exception you need a minimum api version 11. Otherwise perhaps eclipse is to blame? All I know is that this code is correct and should be executing without any issues.

Are you sure this is the first use of networking in your application?

If you are connecting to a server usually at that time NetworkOnMainThreadException should be thrown. Try adding a log statement before the try and see if it shows up. If it does not the Exception is thrown earlier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM