赞
踩
异常对象有两个重要的方法:
获取异常简单的描述信息:(获取调用异常构造方法时输入的String s)
exception.getMessage()
打印异常追踪的堆栈信息:
exception.printStackTrace()
public class ExceptionTest05 { public static void main(String[] args) { NullPointerException npe = new NullPointerException("空指针异常"); //获取异常简单的描述信息:(异常构造方法中的String s) String str = npe.getMessage(); System.out.println(str); //空指针异常 //打印异常追踪的堆栈信息 //java后台打印异常堆栈追踪信息的时候,采用了异步线程的方式打印的 //打印之后并不会影响后续程序的运行 npe.printStackTrace(); //用来体现打印异常追踪的堆栈信息 与 hello world 是异步进行的 for (int i = 0; i < 1000; i++) { System.out.println("i = " + i); } System.out.println("hello world"); } }
import java.io.FileInputStream; import java.io.FileNotFoundException; public class ExceptionTest06 { public static void main(String[] args) { try { m1(); }catch (FileNotFoundException e) { //在实际开发中,应养成打印 异常堆栈追踪信息 的好习惯 e.printStackTrace(); /* 打印信息: java.io.FileNotFoundException: C:\Gam\123.txt (系统找不到指定的路径。) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:212) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:154) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:109) at exception.ExceptionTest06.m2(ExceptionTest06.java:22) at exception.ExceptionTest06.m1(ExceptionTest06.java:18) at exception.ExceptionTest06.main(ExceptionTest06.java:9) */ } //在catch捕捉后可以继续执行 //不耽误程序的执行,很健壮(服务器不会因为遇到异常而宕机) System.out.println("main over"); } private static void m1() throws FileNotFoundException { m2(); } private static void m2() throws FileNotFoundException { new FileInputStream("C:\\Gam\\123.txt"); } } //运行结果: java.io.FileNotFoundException: C:\Gam\123.txt (系统找不到指定的路径。) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:212) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:154) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:109) at exception.ExceptionTest06.m2(ExceptionTest06.java:34) at exception.ExceptionTest06.m1(ExceptionTest06.java:30) at exception.ExceptionTest06.main(ExceptionTest06.java:9) main over Process finished with exit code 0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。