如何存储错误异常消息

时间:2015-08-29 16:15:12

标签: java

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

尝试并抓住部分

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


    try {

      //method and code go here



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

3 个答案:

答案 0 :(得分:9)

您可以在异常对象上调用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
}

答案 1 :(得分:2)

您可以用来获取错误消息:

e.getMessage();

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

String message = e.getMessage();

答案 2 :(得分:1)

您可以使用toString()异常类方法,如下所示:

String message = e.toString();

您将获得有关类名,区域设置消息和错误消息的信息。以下是比getMessage方法更详细的信息。

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