Java中关于异常的一些问题(二)

来源:互联网 发布:php 访问sqlserver 编辑:程序博客网 时间:2024/05/22 04:35

所有的异常对象都包含了如下几种常用的方法

getMessage():返回该异常的详细描述字符串。

printStackTrace():将该异常的跟踪栈信息输出到标准错误输出。

printStackTrace(PrintStream s): 将该异常跟踪栈信息输出到指定输出流。

getStackTrace(): 返回该异常的跟踪栈信息。

程序演示:

import java.io.*;public class AccessExceptionMsg{public static void main(String[] args){try{FileInputStream fis = new FileInputStream("a.txt");}catch (IOException ioe){System.out.println(ioe.getMessage());ioe.printStackTrace();}}}

使用finally回收资源:

finally块必须位于所有的catch块之后。

import java.io.*;public class FinallyTest{public static void main(String[] args){FileInputStream fis = null;try{fis = new FileInputStream("a.txt");}catch (IOException ioe){System.out.println(ioe.getMessage());// return语句强制方法返回return ;       // ①// 使用exit来退出虚拟机// System.exit(1);     // ②}finally{// 关闭磁盘文件,回收资源if (fis != null){try{fis.close();}catch (IOException ioe){ioe.printStackTrace();}}System.out.println("执行finally块里的资源回收!");}}}
如果在异常处理代码中使用了System.exit(1)语句来退出Java虚拟机,那么finally块将不再执行。

通常情况下不要在finally块中使用如return 或throw等导致方法终止的语句,一旦使用后将会导致try块和catch块中的return 、throw语句失效。

1 0
原创粉丝点击