Java教程

Java打印异常堆栈信息,定位异常调用位置

本文主要是介绍Java打印异常堆栈信息,定位异常调用位置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
	public static void main(String[] args) {
		try {
			throw new Exception("Exception Test!");
		} catch (Exception ex) {
			System.out.println("--- getMessage ---");
            System.out.println(ex.getMessage());
            System.out.println();
            System.out.println("--- toString ---");
            System.out.println(ex.toString());
            System.out.println();
            System.out.println("--- printStackTrace ---");
            StringWriter stringWriter = new StringWriter();
            PrintWriter printWriter = new PrintWriter(stringWriter);
            ex.printStackTrace(printWriter);
            System.out.println(stringWriter.toString());
            System.out.println();
            System.out.println("--- printStackTrace DIY ---");
            System.out.println(ex.getClass().getName() + ": " + ex.getMessage());
            StringBuilder sbException = new StringBuilder();
            for (StackTraceElement ele : ex.getStackTrace()) {
                sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n",
                    ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));;
            }
            System.out.println(sbException);
			
			StackTraceElement stackTraceElement= ex.getStackTrace()[0];
			System.err.println("File="+stackTraceElement.getFileName());
			System.err.println("Method="+stackTraceElement.getMethodName());
			System.err.println("Line="+stackTraceElement.getLineNumber());
		}
	}
这篇关于Java打印异常堆栈信息,定位异常调用位置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!