尝试捕获不捕获异常

时间:2013-08-01 10:48:08

标签: android try-catch toast

如果网络通话不可用,我正试图阻止应用程序崩溃。

如果网络通话可用,那么我想点击按钮继续进入下一个活动。捕获应该显示一个吐司。

然而,该应用仍在崩溃,而不是显示吐司

这是我的代码: -

public void GoToStation(View v)
{

        try {

            Intent myIntent = new Intent(
                             MainActivity.this, CustomizedListViewStation.class);
            startActivityForResult(myIntent, 0);
        } catch (Exception myIntent) {
            // TODO Auto-generated catch block
            Context context = getApplicationContext();
            CharSequence text = "There is no data for this Community";
            int duration = Toast.LENGTH_LONG;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }

logcat的: -

08-01 12:36:56.944: E/AndroidRuntime(32556): FATAL EXCEPTION: main
08-01 12:36:56.944: E/AndroidRuntime(32556): java.lang.RuntimeException: Unable to start     activity     ComponentInfo{police.uk.greatermanchesterpoliceandroid/police.uk.greatermanchesterpoliceandroid.CustomizedListViewStation}: android.os.NetworkOnMainThreadException
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.os.Looper.loop(Looper.java:137)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.main(ActivityThread.java:4898)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.lang.reflect.Method.invokeNative(Native Method)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.lang.reflect.Method.invoke(Method.java:511)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at dalvik.system.NativeStart.main(Native Method)
08-01 12:36:56.944: E/AndroidRuntime(32556): Caused by: android.os.NetworkOnMainThreadException
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at police.uk.greatermanchesterpoliceandroid.XMLParser.getXmlFromUrl(XMLParser.java:45)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at police.uk.greatermanchesterpoliceandroid.CustomizedListViewStation.onCreate(CustomizedListViewStation.java:108)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.Activity.performCreate(Activity.java:5206)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-01 12:36:56.944: E/AndroidRuntime(32556):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
08-01 12:36:56.944: E/AndroidRuntime(32556):    ... 11 more
08-01 12:37:05.694: I/Process(32556): Sending signal. PID: 32556 SIG: 9

3 个答案:

答案 0 :(得分:1)

而不是先检查互联网连接。删除try-catch块并在if代码中调用isOnline函数 - > if(isOnline()){}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

用这个替换你的try-catch:

if (isOnline()){
    Intent myIntent = new Intent(MainActivity.this, CustomizedListViewStation.class);
    startActivityForResult(myIntent, 0);
} 

else {            
    Context context = getApplicationContext();
    CharSequence text = "There is no data for this Community";
    int duration = Toast.LENGTH_LONG;
    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

答案 1 :(得分:1)

如果您有200%确定需要在主线程中进行网络活动,请使用此命令,使用:

if (android.os.Build.VERSION.SDK_INT > 9) {
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
}

否则,请查看ThreadsAsyncTasks

答案 2 :(得分:0)

因为你在主线程上运行代码所以它正在抛出NetworkOnMainThreadException。这不在您的代码中,因此您无法捕获它,也不应该尝试捕获它,因为您的应用程序永远不会工作,因为它永远不会尝试由于此错误建立网络连接。

您需要在单独的线程(例如ASyncTask)中执行网络活动,并且不再抛出此异常。

此异常的原因是网络活动通常会导致应用程序出现延迟,因为网络调用往往会阻塞,直到完成为止。如果在主线程上执行网络活动,则应用程序的用户可能会收到ANR(应用程序无响应)消息,这意味着用户可以强制关闭您的应用程序,因为它看起来好像您的应用程序不再响应任何内容在后台它正在进行网络活动。