Java Throwable to String getStackTrace(Throwable exc)

Here you can find the source of getStackTrace(Throwable exc)

Description

Creates and array of strings containing the exception traceback information of a Throwable.

License

Open Source License

Parameter

Parameter Description
exc the exception

Return

a string array of the traceback information.

Declaration

public static String[] getStackTrace(Throwable exc) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2001, 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://  w  w  w. ja v  a  2  s  .c o  m
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

import java.io.BufferedReader;

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

import java.util.Vector;

public class Main {
    /**
     * Creates and array of strings containing the exception traceback information of
     * a Throwable.  This is the same traceback data that is displayed by exc.printStackTrace().
     * @param exc the exception
     * @return a string array of the traceback information.
     */
    public static String[] getStackTrace(Throwable exc) {
        Vector lines = new Vector();
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);

        exc.printStackTrace(printWriter);

        try {
            printWriter.close();
            stringWriter.close();
        } catch (Exception nestedExc) {
            return new String[0];
        }

        StringReader stringReader = new StringReader(stringWriter.toString());
        BufferedReader reader = new BufferedReader(stringReader);
        String line = null;

        try {
            line = reader.readLine();

            while (line != null) {
                lines.add(line.trim());
                line = reader.readLine();
            }
        } catch (Exception nestedExc) {
            return new String[0];
        }

        return (String[]) lines.toArray(new String[0]);
    }
}

Related

  1. getStackTrace(Throwable e)
  2. getStackTrace(Throwable e)
  3. getStackTrace(Throwable ex)
  4. getStackTrace(Throwable ex)
  5. getStackTrace(Throwable ex)
  6. getStackTrace(Throwable exception)
  7. getStackTrace(Throwable exception)
  8. getStackTrace(Throwable pException)
  9. getStackTrace(Throwable pThrowable_)