传统try{}catch
如果{}中的代码块出现了异常,会被catch捕获,然后执行catch中的代码,接着执行finally中的码,其中catch中的代码有了异常才会被执行,finally中的代码无论有没有异常都会被执行
String file="G:\\aaa.txt";
try {
InputStream inputStream=new FileInputStream(file);
int temByte;
while ((temByte=inputStream.read())!=-1){
System.out.println(temByte);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try(){}catch
在()里的代码一般放的是对资源的申请,如果{}中的代码出项了异常,()中的资源就会被关闭,运行结束时资源也会被释放
String file="G:\\aaa.txt";
try(InputStream inputStream=new FileInputStream(file)) {
int temByte;
while ((temByte=inputStream.read())!=-1){
System.out.println(temByte);
}
}catch (Exception e){
e.printStackTrace();
}