我们再开发得时候经常需要输出异常信息.不如看看以下代码:
public void test(){ try{ int i = 1; int b = 0 ; int c = i/b; }catch (Exception ex){ Log.d("2635", "test: "+ex.getMessage()); } }
上面这个代码会输出 ,那么看到这个东西我们就知道程序错误是由于除0了 .
test: divide by zero
但是,实际项目一般很大.我们需要定位到具体哪个类,哪一行.就跟我们再IDE上面看到得异常一样,比如这样.除了知道原因,我们还要知道第几行.
public void test(){ try{ int i = 1; int b = 0 ; int c = i/b; }catch (Exception ex){ Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause!=null){ cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.close(); String result = writer.toString(); Log.d("2635", "test: "+result); } }
修改后,输出得日志就是这样了,这样我们就可以定位到错误得代码