62,614
社区成员
发帖
与我相关
我的任务
分享
InputStream in = ...;
try{
try{
code may thorw exceptions
}finally{
in.close();
}
}catch(IOException e){
do some action
}
public static void throwException(){
File f = null;
FileInputStream fis = null;
try{
try{
f = new File("abc");
// 这个文件是不存在的,所以应该抛出FileNotFoundException
fis = new FileInputStream(f);
fis.read();
}finally{
fis.close();
}
}catch(FileNotFoundException e){
System.out.println("file not found");
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
public static void throwException1(){
File f = null;
FileInputStream fis = null;
try{
f = new File("abc");
// 这个文件是不存在的,所以应该抛出FileNotFoundException
fis = new FileInputStream(f);
fis.read();
}catch(FileNotFoundException e){
System.out.println("file not found");
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} finally{
try{ // 在finally对异常进行单独处理
if(fis!=null){ //非空才关闭
fis.close();
}
}catch(Exception e){
//异常处理,并写入日志
}
}
}
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream("c:/test.txt");
try {
OutputStream out = new FileOutputStream("c:/test1.txt");
try {
int len = 0;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
} finally {
if (out != null) {
out.close();
}
}
} finally {
if (in != null) {
in.close();
}
}
}
public static void throwException(){
File f = null;
FileInputStream fis = null;
try{
f = new File("abc");
// 这个文件是不存在的,所以应该抛出FileNotFoundException
fis = new FileInputStream(f);
fis.read();
}catch(FileNotFoundException e){
System.out.println("file not found");
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} finally{
try{
fis.close();
}catch(Exception e){
//异常处理,并写入日志
.......
}
}
}