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...
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...
为了获取异常的StackTrace信息,并将其记录到日志文件中,我们可以修改捕获异常的代码如下: try{doSomething();}catch(CustomExceptione){// 获取异常的StackTrace信息StringWritersw=newStringWriter();PrintWriterpw=newPrintWriter(sw);e.printStackTrace(pw);StringstackTrace=sw.toString();// 将StackTrace信息记录到日志...
在下面的程序中,我们创建一个NullPointerException并在将其转换为String后打印其堆栈跟踪。 NullPointerException npe = new NullPointerException("Custom error"); String errorStr = null; try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) { npe.printStackTrace(pw); errorSt...
Java program to convert error stack trace to String. StackTrace to String conversion may be useful to print stack trace in custom logs.
}/*** 过滤不重要的StackTrace,只保留与项目相关的StackTrace * *@throwsException*/publicstaticString getExceptionStackTrace(Throwable e, String includesRegex, String excludes) { StringWriter sw=newStringWriter(); e.printStackTrace(newPrintWriter(sw)); ...
包含了异常的类型、异常的原因、异常出现的位置、在开发和调试阶段都得使用printStackTrace。 public String getMessage():获取发生异常的原因。 2.2 Error 和 Exception Throwable可分为两类:Error和Exception。分别对应着java.lang.Error与java.lang.Exception两个类。
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...
*/publicstaticvoidmain(String[]args)throws FileNotFoundException{File file=newFile("d:/q11.txt");FileInputStream inputStream=newFileInputStream(file);//try-catch-finally 处理异常try{inputStream.read();}catch(IOException e){// 打印异常信息,可以在此自定义异常提示e.printStackTrace();}finally{try...
1. printStackTrace() import java.io.*; class Main { public static void main (String[] args) { int a=5; int b=0; try{ System.out.println(a/b); } catch(ArithmeticException e){ e.printStackTrace(); } } } 输出:此方法以异常名称的格式打印异常信息:异常描述、堆栈跟踪。 java.lang.Ar...