简体   繁体   中英

Java exception handling get console error message

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

now I have java code with following scenario:

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.

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

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.

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();
}

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

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 )

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

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 setStackTrace and using the printStackTrace() in first

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();
 }
}

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());
        }
     }

}

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.

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

 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();

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM