比方说,在我的Java应用程序中,throws我的主类中有一个Exception,我试着抓住我的代码.在我的catch部分中,我有一个代码将在我的应用程序中显示异常.我想知道的是,无论如何我可以存储控制台中显示的此异常消息,然后将此异常消息发送到我的电子邮件地址?我得到了电子邮件连接部分工作,我需要做的就是找到存储该错误异常消息的方法.帮助将不胜感激.
试着抓住一部分
public static void main (String[] args) throws Exception{
try {
//method and code go here
}
catch (Exception e){
//Exception
throw e;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以调用getMessage()异常对象来获取消息:
catch (Exception e) {
String message = e.getMessage();
// Do whatever with the message, for example e-mail it somewhere
}
Run Code Online (Sandbox Code Playgroud)
如果您想要异常的完整堆栈跟踪,那么将其转换为字符串会更多一些工作:
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
}
Run Code Online (Sandbox Code Playgroud)