public static void main(String[] args) { try { String[] arr = {"111", "222"}; arr[2] = "fff"; } catch (Exception e) { String info = getErrorInfoFromException(e); System.out.println(info); } } public static String getErrorInfoFromException(Exception e) { try { StringWriter sw...
e.printStackTrace(pw); return "\r\n" + sw.toString() + "\r\n"; } catch (Exception e2) { return "bad getErrorInfoFromException"; } } } 控制台上输出的消息如下所示: java.lang.ArrayIndexOutOfBoundsException: 2 at com.test1.T010.main(T010.java:14)...
* 将异常信息转化成字符串 * @param t * @return * @throws IOException*/privatestaticString exception(Throwable t) throws IOException{if(t ==null)returnnull; ByteArrayOutputStream baos=newByteArrayOutputStream();try{ t.printstacktrace(newPrintStream(baos)); }finally{ baos.close(); }returnbaos....
package com.test1; import java.io.PrintWriter; import java.io.StringWriter; public class T010 { /** * @param args */ public static void main(String[] args) { try { String[] arr = {"111", "222"}; arr[2] = "fff"; } catch (Exception e) { String info = getErrorInfoFromExcepti...
让我们通过一个示例代码来演示e.printStackTrace()的使用方法。假设我们有以下的 Java 代码: 代码语言:javascript 代码运行次数:0 运行 publicclassExceptionExample{publicstaticvoidmain(String[]args){try{// 调用可能会引发异常的方法divideByZero();}catch(Exception e){// 打印异常的调用栈信息e.printStackTrace...
Java program to convert error stack trace to String. StackTrace to String conversion may be useful to print stack trace in custom logs.
printStackTrace()方法将会输出异常的堆栈跟踪信息到标准错误流。 下面是一个完整的示例代码: public class Example { public static void main(String[] args) { try { // 可能会抛出异常的代码 int result = 10 / 0; } catch (Exception e) { // 捕获异常并打印堆栈跟踪信息 e.printStackTrace(); } }...
ByteArrayOutputStream baos=newByteArrayOutputStream();e.printStackTrace(newPrintStream(baos));String exception=baos.toString();System.out.println("baos:"+exception); 这里使用了文件流,等同于把e.printStackTrace()的内容打印到一个文件中,然后再把内容付给一个字符串,最后就可以把logger.error(exception)把...
/** * 将异常信息转化成字符串 * @param t * @return * @throws IOException */ private static String exception(Throwable t) throws IOException{ if(t == null) return null; ByteArrayOutputStream baos = new ByteArrayOu
public static void main(String[] args) { try { g(); }catch(Exception e) { e.printStackTrace(); } } } 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 这个例子的输出如下: java.lang.Exception: 出问题啦!