Java基础(13):异常

来源:互联网 发布:mac 设置屏幕待机时间 编辑:程序博客网 时间:2024/05/17 04:48

异常

        造成程序无法继续运行的错误输入或输出即为异常。异常分为三种:编译异常,运行异常和错误。

要想捕获异常,可以用try/catch语句。

public class ExceptionTest {    @Test    public void test() {        read("C://test/txt");    }    public void read(String filename){            try {            InputStream in=new FileInputStream(filename);            int len;            if((len=in.read())!=-1){                System.out.println("finish");            }            in.close();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

程序抛出异常后,就会终止运行。使用finally,可以在抛出异常后继续运行finally内的语句。

public class ExceptionTest {@Testpublic void test() {try {read("C://test/txt");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void read(String filename) throws IOException {InputStream in = null;try {in=new FileInputStream(filename);int len;if((len=in.read())!=-1){System.out.println("finish");}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{in.close();}}}



0 0
原创粉丝点击