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 Strin
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....
代码运行次数:0 publicclassExceptionExample{publicstaticvoidmain(String[]args){try{// 调用可能会引发异常的方法divideByZero();}catch(Exception e){// 打印异常的调用栈信息e.printStackTrace();}}publicstaticvoiddivideByZero(){int a=5;int b=0;int result=a/b;}} 在上述代码中,我们故意将除数b设置...
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 = getErrorInfoFrom...
printStackTrace()方法将会输出异常的堆栈跟踪信息到标准错误流。 下面是一个完整的示例代码: public class Example { public static void main(String[] args) { try { // 可能会抛出异常的代码 int result = 10 / 0; } 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.
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: 出问题啦!
/** * 将异常信息转化成字符串 * @param t * @return * @throws IOException */ private static String exception(Throwable t) throws IOException{ if(t == null) return null; ByteArrayOutputStream baos = new ByteArrayOu
lang.ArithmeticException: / by zero at com.example.Main.main(Main.java:5) 这告诉我们异常发生在Main类的main方法中,具体在代码的第5行。总结:在处理Java异常时,e.getMessage()、e.toString()和e.printStackTrace()都有其特定的用途。e.getMessage()返回详细的异常消息,有助于了解发生了什么问题。e....