【问题标题】:android - how to get an exception's class and method name within which it occurredandroid - 如何获取发生异常的类和方法名称
【发布时间】:2011-07-27 16:06:03
【问题描述】:

大家好,我想在一个中心位置处理我的 android 应用程序中的所有异常,即应用程序类

我的应用程序类中有如下方法:

public void HandleException(Exception e)
{
    String appName = getString(R.string.app_name);
    String className = ""; // magic method to find out the original class name where the exception occurred
    String methodName = ""; // magic method to find out the original method name where the exception occurred
    Log.e(appName, className + " : " + methodName + " - " + e.getMessage());
}

现在缺少的只是神奇的方法,它使用发生异常的原始类和方法填充我的 className 和 methodName 变量

谁能帮忙

提前谢谢...

【问题讨论】:

    标签: java android logging exception-handling


    【解决方案1】:

    使用e.getStackTrace (),通过这个数组搜索类名和你的包名(使用StackTraceElement.getClassName())——这是你的类名“魔术方法”。然后用StackTraceElement.getMethodName()获取方法名。

    【讨论】:

    • 当你写 - 用你的包名搜索类名 - 我怎么知道要搜索哪个类名,因为任何类都可能发生异常......
    • 你在异常中的类名应该包含你的包名,所以你需要以com.raj.application为例进行搜索。 if (element.getClassName().contains(yourPackageName)){//it's your class}
    猜你喜欢
    • 1970-01-01
    • 2021-08-19
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2012-09-25
    • 2020-12-26
    • 2016-03-20
    相关资源
    最近更新 更多