【问题标题】:How to Store an Error Exception message如何存储错误异常消息
【发布时间】:2015-08-29 16:15:12
【问题描述】:

假设在我的 Java 应用程序中,我的主类中有一个 throws 异常,我尝试并抓住我的代码。在我的捕获部分中,我有一个代码将在我的应用程序中显示一个异常。我想知道的是,无论如何我可以存储控制台中显示的异常消息,然后将此异常消息发送到我的电子邮件地址吗?我得到了电子邮件连接部分的工作,我需要做的就是找到一种方法来存储该错误异常消息。我们将不胜感激。

试着抓住一部分

public static void main (String[] args) throws Exception{


    try {

      //method and code go here



    }
    catch (Exception e){
        //Exception
         throw e;
    }
}

【问题讨论】:

  • FYI-U r 使用 try catch 块处理异常,所以从 main 方法不需要抛出异常。
  • 哦,对了,我忘了,谢谢你指出:)

标签: java


【解决方案1】:

你可以在异常对象上调用getMessage()来获取消息:

catch (Exception e) {
    String message = e.getMessage();
    // Do whatever with the message, for example e-mail it somewhere
}

如果您想要异常的完整堆栈跟踪,则将其放入字符串中需要做更多的工作:

catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    String stackTrace = sw.toString();
    // do whatever you want to do with stackTrace
}

【讨论】:

  • 非常感谢,这就是我要找的!
  • 第一个选项应该是e.toString() 来获取异常名称。单独的消息通常毫无意义,例如这个表达式(new int[0])[1] 抛出ArrayIndexOutOfBoundsException 和消息1
  • 我们不能使用:String stackTrace = e.getStackTrace().toString(); (我不确定)
  • @Saud getStackTrace() 返回一个数组,而数组的toString()打印元素。
【解决方案2】:

你可以用来获取错误信息:

e.getMessage();

如果您想存储消息,只需执行以下操作:

String message = e.getMessage();

【讨论】:

    【解决方案3】:

    你可以使用异常类的toString()方法,像这样:

    String message = e.toString();
    

    您将获得有关类名、语言环境消息和错误消息的信息。这里有比getMessage 方法更详细的信息。

    要存储异常消息以供进一步使用,您也可以创建类字段。

    【讨论】:

    • 也可以用""+e作为快捷键
    • @shieldgenerator7,Stringcast 有一个不好的方法
    • 为什么?它绕过任何可能的 NullPointerExceptions
    • @shieldgenerator7,如果我们在catch 语句中,我们不会得到NPE
    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多