您的位置:首页 > 编程语言 > Java开发

Java基础(13):异常

2015-11-03 22:57 337 查看
异常

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

要想捕获异常,可以用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 {

@Test
public void test() {
try {
read("C://test/txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.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 block
e.printStackTrace();
}finally{
in.close();

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: