异常
造成程序无法继续运行的错误输入或输出即为异常。异常分为三种:编译异常,运行异常和错误。
要想捕获异常,可以用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();
}
}
}
本文详细介绍了程序中异常的概念及其分类,并通过示例代码展示了如何使用try/catch/finally语句来处理异常,确保程序的健壮性和稳定性。

被折叠的 条评论
为什么被折叠?



