java Java异常处理获取控制台错误信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26336437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:44:36  来源:igfitidea点击:

Java exception handling get console error message

javaexception-handling

提问by Piyush Chaudhari

I want to get error message using java when exception are generated.

我想在生成异常时使用 java 获取错误消息。

now I have java code with following scenario:

现在我有以下场景的java代码:

method first(){

     try{
        second();
     }catch(Exception e){
        System.out.println("Error:> "+e)
     }

}


method second(){

     try{
       my code
     }catch(Exception e){
        throw new Exception("Exception generate in second method",e);
     }

}

now when the first method execute then I get only "Exception generate in second method" message but there is some other message printed on console by java so how to get that console error message.

现在,当第一个方法执行时,我只得到“在第二个方法中生成异常”消息,但是java在控制台上打印了一些其他消息,因此如何获取该控制台错误消息。

Note: I have already try with e.getMessage(); and e.printStackTrace();

注意:我已经尝试过 e.getMessage(); 和 e.printStackTrace();

回答by Rob Meeuwisse

Every exception has a cause that you can get with getCause(). You can go recursively down them until you get to the root cause. Here is your example with a utility that dumps the exception with all its causes like the console does.

每个异常都有一个你可以得到的原因getCause()。您可以递归地查找它们,直到找到根本原因。这是您的示例,其中包含一个实用程序,该实用程序可以像控制台一样转储异常及其所有原因。

private void first() {
    try  {
        second();
    } catch (Exception ex) {
        Log.e("CATCH", getExceptionDump(ex));
    }
}

private void second() {
    try {
        throw new UnsupportedOperationException("We don't do this.");
    } catch (Exception ex) {
        throw new RuntimeException("Exception in second()", ex);
    }
}

private String getExceptionDump(Exception ex) {
    StringBuilder result = new StringBuilder();
    for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
        if (result.length() > 0)
            result.append("Caused by: ");
        result.append(cause.getClass().getName());
        result.append(": ");
        result.append(cause.getMessage());
        result.append("\n");
        for (StackTraceElement element: cause.getStackTrace()) {
            result.append("\tat ");
            result.append(element.getMethodName());
            result.append("(");
            result.append(element.getFileName());
            result.append(":");
            result.append(element.getLineNumber());
            result.append(")\n");
        }
    }
    return result.toString();
}

回答by underdog

I believe this is the console message you want to achieve:

我相信这是您想要实现的控制台消息:

Error:> java.lang.Exception: Exception generate in second method

Try this code, when the catch block of the second method throws an exception the second method should declare it as throws or put a nested try catch within the catch block.

试试这段代码,当第二个方法的 catch 块抛出异常时,第二个方法应该将其声明为 throws 或在 catch 块中放置一个嵌套的 try catch。

The exception is propagated to the first() method which is handled by its catch block.

异常被传播到由其 catch 块处理的 first() 方法。

 public class Test {

        public void first() {

            try {
                second();
            } catch (Exception e) {
                System.out.println("Error:> " + e);
            }

        }

        public void second() throws Exception {

            try {
                throw new Exception();
            } catch (Exception e) {
                throw new Exception("Exception generate in second method", e);
            }
        }

        public static void main(String ars[]) {

            Test test = new Test();

            test.first();

        }
    }

回答by Atul Sharma

The message in the Exception constructor argument is not printed in the exception detail. You can simply use this code to print the message :

异常构造函数参数中的消息不会打印在异常详细信息中。您可以简单地使用此代码打印消息:

method first(){

     try{
        second();
     }catch(Exception e){
        System.out.println("Error:> "+e.getMessage())
     }

}

Hope this solves your problem

希望这能解决您的问题

回答by Kraiss

Why you cannot use print stack trace ?

为什么不能使用打印堆栈跟踪?

Because A throwable contains a snapshot of the execution stack of its thread at the time it was created.(see Throwable)

因为A throwable contains a snapshot of the execution stack of its thread at the time it was created.(见Throwable

It implies that, if you want to print the stack trace you need to use the printStackTrace()method BUT in your second method !

这意味着,如果您想打印堆栈跟踪,您需要printStackTrace()在第二种方法中使用方法 BUT !

method second(){
  try {
    my code
  } catch(Exception e) {
    e.printStackTrace();
    throw new Exception("Exception generate in second method",e);
  }
 }

Or using a the tricky method setStackTraceand using the printStackTrace()in first

或者使用棘手的方法setStackTraceprintStackTrace()首先使用in

method second(){
  try {
    my code
  } catch(Exception e) {
    Exception ex = new Exception("Exception generate in second method",e);
    ex.setStackTrace(e);
    throw ex;
  }
 }


method first(){

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

回答by David ten Hove

You can print the cause of the exception you get. Try this:

您可以打印您获得的异常的原因。试试这个:

method first(){

     try{
        second();
     }catch(Exception e){
        System.out.println("Error:> "+e);
        if (e.getCause() != null) {
            System.out.println("Cause:> " + e.getCause());
        }
     }

}