Java Throwable to String getStackTraceLines(Throwable t, int numLines)

Here you can find the source of getStackTraceLines(Throwable t, int numLines)

Description

return the top n lines of this stack trace Example: ExceptionUtil.getStackTraceLines(exception, 10);

License

Apache License

Declaration

public static String getStackTraceLines(Throwable t, int numLines) 

Method Source Code


//package com.java2s;
/*//w  ww . jav  a2s .com
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

import java.io.PrintWriter;
import java.io.StringWriter;

import java.util.StringTokenizer;

public class Main {
    /**
     * return the top n lines of this stack trace
     *
     * Example: ExceptionUtil.getStackTraceLines(exception, 10);
     */
    public static String getStackTraceLines(Throwable t, int numLines) {
        StringTokenizer tokens = new StringTokenizer(toString(t), "\n\r");

        StringBuilder trace = new StringBuilder();

        for (int i = 0; i < numLines; i++) {
            String token = tokens.nextToken();
            trace.append(token);
            trace.append("\n");
        }

        return trace.toString();
    }

    /**
     * return the stack trace in a String
     */
    public static String toString(Throwable t) {
        StringWriter strWrt = new StringWriter();
        t.printStackTrace(new PrintWriter(strWrt));

        return strWrt.toString();
    }
}

Related

  1. getStackTraceAsString(Throwable throwable)
  2. getStackTraceAsText(Throwable t)
  3. getStackTraceFromBaseException(Throwable exc)
  4. getStackTraceFromThrowable(Throwable t)
  5. getStackTraceInString(Throwable throwable)
  6. getStackTraceOnly(Throwable throwable)
  7. getStackTraceString(final Throwable currentEx)
  8. getStackTraceString(Throwable cause, String delimiter, int maxLines)
  9. getStackTraceString(Throwable e)