Can't Catch NetworkOnMainThreadException

帅比萌擦擦* 提交于 2020-01-15 06:07:10

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/11613287/cant-catch-networkonmainthreadexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!