Android中捕获异常

Iliz:

我收到我的Android Studio中的错误调用一个方法之后。我更好奇,如果错误是什么,我认为这是与否。错误首先讲述至极后关闭并给出了一个致命的异常意外的响应代码500。

我一直试图让来自致命异常,但没有运气的例外。据我了解,我不能赶上意外的响应代码500。

错误

D/NetworkSecurityConfig: No Network Security Config specified, using platform default
E/Volley: [1668] BasicNetwork.performRequest: Unexpected response code 500 for (website)
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.geotask, PID: 14594
    java.lang.IllegalStateException
        at com.example.geotask.PSHandler$1.onErrorResponse(PSHandler.java:48)
        at com.android.volley.Request.deliverError(Request.java:617)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:104)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Application terminated.

给出错误的代码

try {
    psHandler.addNewUser(name, LoginActivity.this, new RetrievedCallback<Void>() {
        @Override
        public void execute(Void input) {
            Intent intent;
            intent = new Intent(LoginActivity.this, MainActivity.class);
            Toast.makeText(LoginActivity.this, "New account created", Toast.LENGTH_SHORT).show();
            startActivity(intent);
            finish();
        }
    });
} catch (IllegalStateException e) {
}

我删除它指的是网站。正如你所看到的,我试图抓住那就是在logcat中给出可能的错误,但我不知道如果我的能力。我想知道如果我能够防止错误从logcat中的。

胡里奥E.罗德里格斯小屋:

为什么你不能捕获该异常的原因是因为你试图在那里实际发生的外部抓住它的方法:

try {
    psHandler.addNewUser(name, LoginActivity.this, new RetrievedCallback<Void>() {
        @Override
        public void execute(Void input) {
            throw new IllegalStateException();
        }
    });
} catch (IllegalStateException e) {
    // This line will never be reached because the exception 
    // is not thrown here, but inside the callback method
}

相反,你应该添加try/catch回调方法里面:

psHandler.addNewUser(name, LoginActivity.this, new RetrievedCallback<Void>() {
    @Override
    public void execute(Void input) {
        try {
            throw new IllegalStateException();
        } catch (IllegalStateException e) {
            // This line will be reached
        }
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章