异常
造成程序无法继续运行的错误输入或输出即为异常。异常分为三种:编译异常,运行异常和错误。
要想捕获异常,可以用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();
}
}
}