Java之异常信息的三种打印方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38225558/article/details/82110554
  1. String getMessage() :返回此 throwable 的详细消息字符串。 
  2. String toString() : 返回此 throwable 的简短描述。 
  3. void printStackTrace():将此 throwable 及其追踪输出至标准错误流。 (即 调用此方法会把完整的异常信息打印到控制台)

ex:

/**
 * String getMessage() :返回此 throwable 的详细消息字符串。 
 * String toString() : 返回此 throwable 的简短描述。 
 * void printStackTrace():将此 throwable 及其追踪输出至标准错误流。 (即 调用此方法会把完整的异常信息打印到控制台)
 * @author 郑清
 */
public class Demo {
	public static void main(String[] args) {
		test(6,0);
	}
	public static void test(int a,int b){
		try{
			System.out.println(a/b);
		}catch(Exception e){
			//catch里面是出现异常的处理方式    下面err是以红色打印信息
			System.err.println(e.getMessage());//打印异常原因                   ==》  一般给用户看
			System.err.println(e.toString());//打印异常名称以及异常原因  ==》 很少使用
			e.printStackTrace();//打印异常原因+异常名称+出现异常的位置      ==》 给程序员debug的时候看
		}
		System.out.println("===try-catch结束===");
	}
}

运行结果图:

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/82110554