//返回此可抛出对象的详细信息消息字符串
public String getMessage() //将此可抛发对象及其回溯到标准错误流。此方法在错误输出流上打印此 Throwable 对象的堆栈跟踪
//最为详细
public void printStackTrace()
//返回此可抛件的简短说明
public String toString()
对于1/0这个异常
try{int i = 1/0;} catch(Exception e){System.out.println("e = " + e);System.out.println("-----------------");System.out.println("e.getMessage() = " + e.getMessage());System.out.println("-----------------");System.out.println("e.getStackTrace() = " + Arrays.toString(e.getStackTrace()));System.out.println("-----------------");System.out.println("e.getLocalizedMessage() = " + e.getLocalizedMessage());System.out.println("-----------------");System.out.println("e.getCause() = " + e.getCause());System.out.println("-----------------");System.out.println("e.getClass() = " + e.getClass());System.out.println("-----------------");System.out.println("e.getSuppressed() = " + Arrays.toString(e.getSuppressed()));}
e = java.lang.ArithmeticException: / by zero
-----------------
e.getMessage() = / by zero
-----------------
e.getStackTrace() = [省略27行,com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)]
-----------------
//可能的原因
e.getCause() = null
-----------------
//一个数组,其中包含为传递此异常而禁止显示的所有异常。
//就是用try捕获却不做事的
e.getSuppressed() = []
让控制台的报错信息更加的见名知意
简化释放资源的步骤
自动释放的类需要实现autocloseable的接口
这样在特定情况下会自动释放,还有的就是stream流中提到过。
try(创建对象资源1;创建对象资源2){}catch(){
}
例如这样的代码可以改写成
BufferedInputStream b = null;
try {b = new BufferedInputStream(new FileInputStream(""));
}catch (Exception e) {e.printStackTrace();
}finally {if (b!=null) {try {b.close();} catch (IOException e) {throw new RuntimeException(e);}}
}
try (BufferedInputStream b = new BufferedInputStream(new FileInputStream(""));){}catch (Exception e) {e.printStackTrace();
}
创建对象1
创建对象2
try(变量名1;变量名2){
}catch(){
}
上面的代码可以改写成,
不过需要注意的是创建对象也需要异常处理,我们这里选择抛出
public void testTryWithResource() throws FileNotFoundException {BufferedInputStream b = new BufferedInputStream(new FileInputStream(""));try (b) {} catch (Exception e) {e.printStackTrace();}
}