简体   繁体   English

在Android中发生异常时,如何让程序自动打印堆栈跟踪

[英]How can I make program print a stack trace automatically when an Exception occurs in Android

Is there a way I can automatically print a stack trace when Exception occurs? 有没有办法在Exception发生时自动打印堆栈跟踪? I understand I can do so by manually surrounding a block with a try-catch statement, but there's no prior-knowledge where an exception would happen in a program, and doing it in suspicious region block by block would be super inefficient, since there're potentially many. 我理解我可以通过try-catch语句手动包围一个块来实现,但是没有先验知识在程序中会发生异常,并且在可疑区域中逐块地执行它将是超级低效的,因为那里'可能很多。 So is there any configuration option or any programmatic way to do so in Android?(like surrounding a try-catch block in the highest level of method?, but what's the highest level of method) 那么在Android中是否有任何配置选项或任何编程方式?(比如在最高级别的方法中包围try-catch块?,但是最高级别的方法是什么)

Define a global exception handler in your Application class and add any code you need to it. Application类中定义全局异常处理程序,并添加所需的任何代码。

Thread.setDefaultUncaughtExceptionHandler(
                new DefaultExceptionHandler(this));

It is recommended that you still re-throw caught exceptions so that the app stops running, because it will be in an unstable state and not doing so can cause the app to freeze up. 建议您仍然重新抛出捕获的异常,以便应用程序停止运行,因为它将处于不稳定状态而不这样做会导致应用程序冻结。

catch (Exception e) {e.printStackTrace();}

The highest level is the Application level I believe. 最高级别是我认为的应用程序级别。 But in general just catch it at the usual activity lifecycle should be sufficient. 但总的来说,只是抓住它在通常的活动生命周期应该足够了。

扩展异常并在自定义异常类中执行任何操作。

There are two major kinds of exceptions: 有两种主要的例外情况:

  1. Exceptions caused by programming errors (eg dereferencing a null reference, ...) 编程错误导致的异常(例如,解除引用空引用,...)
  2. Exceptions caused by the environment (eg user enters 'abc' in a numeric field, network cable was unplugged, ...) 由环境引起的异常(例如,用户在数字字段中输入'abc',网络电缆已拔下,...)

In most of the cases you can't really recover from the first ones. 在大多数情况下,你无法真正从第一个恢复。 (If something unexpectedly went wrong, how can you know what to do to recover safely?) This are usually unchecked exceptions and you don't have to catch them somewhere. (如果出现意外问题,你怎么知道如何安全地恢复?)这通常是未经检查的异常,你不必在某处捕获它们。

Uncaught exceptions are catched by the system/framework and logged automatically! 未捕获的异常会被系统/框架捕获并自动记录!

Take care for the second type of exceptions! 注意第二种例外情况! They are mostly not unchecked and have to be either cached or specified via throws clause. 它们通常不是未经检查的,必须通过throws子句进行缓存或指定。 Handle them, probably log them , and try to recover if possible. 处理它们,可能记录它们 ,并尽可能恢复。

This document explains how you can read the error log and other logs on android devices. 本文档介绍了如何在Android设备上读取错误日志和其他日志。 There are also apps available that can display the log on the device itself. 还有一些应用程序可以显示设备本身的日志。

Also read this basic exception tutorial ! 另请阅读此基本异常教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM