Android使用try…catch…处理异常

在开发过程中,可以预判有些地方难免会出现异常

一、APP解析从服务器获取的数据时,服务器端可能会出错,传递给APP端的数据类型不对,或数据为空,导致APP端出现异常(okhttp)

@Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    Gson gson = new Gson();
                    String json = response.body().string();
                    // 其他后续操作
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DoctorListActivity.this, "服务器数据异常", Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }

            }

猜你喜欢

转载自blog.csdn.net/songzi1228/article/details/81164908