java异常处理的使用。
2011-12-17 15:15
232 查看
package com.robert.test1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * @author Administrator *测试try catch块的执行路径 */ public class TryCatchTest { public static void main(String[] args) { try { InputStream inputStream = new FileInputStream("abc"); inputStream.read(); } catch (FileNotFoundException e) { System.out.println("throw a FileNotFoundException"); } catch (IOException e) { System.out.println("throw a IOException!"); } System.out.println("hello world!"); } } 当文件找不到时:
输出:
throw a FileNotFoundException
hello world!
package com.robert.test1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * @author Administrator *测试try catch块的执行路径 */ public class TryCatchTest { public static void main(String[] args) { try { InputStream inputStream = new FileInputStream("abc"); inputStream.read(); } catch (FileNotFoundException e) { System.out.println("throw a FileNotFoundException"); return; } catch (IOException e) { System.out.println("throw a IOException!"); return; } System.out.println("hello world!"); } }
在catch块中加入return ,当程序遇到异常(FileNotFoundException,IOException)的时候会被返回。即catch后的代码不会被执行。
输出:
throw a FileNotFoundException
package com.robert.test1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * @author Administrator *测试try catch块的执行路径 */ public class TryCatchTest { public static void main(String[] args) { try { InputStream inputStream = new FileInputStream("abc"); inputStream.read(); } catch (FileNotFoundException e) { System.out.println("throw a FileNotFoundException"); return; } catch (IOException e) { System.out.println("throw a IOException!"); return; } finally { System.out.println("finally"); } System.out.println("hello world!"); } }
如果后finally,程序遇到异常(FileNotFoundException,IOException) ,finally块中的代码也会被执行到。
输出:
throw a FileNotFoundException
finally
相关文章推荐
- 学习博文 如何正确使用Java异常处理机制
- 用java实现php式的字典使用方式(未做异常处理)
- 如何正确使用Java异常处理机制
- Java异常处理回顾:使用finally块
- 使用throws处理JAVA异常的简单示例
- Java 中使用 try-catch-finally处理异常
- Java的异常处理及throw的使用
- Java异常处理机制的详细讲解和使用技巧
- Java异常处理之处理未捕获的异常及UncaughtExceptionHandler的使用
- Java - Java语言如何进行异常处理,关键字:throws、throw、try、catch、finally分别如何使用?
- Java异常处理、异常处理使用的一些注意点(例如,基类和子类捕获的顺序问题)
- Java异常处理机制的详细讲解和使用技巧
- 关于Java中使用hessian-3.0.20调用远程服务连接出错异常try catch无法捕捉的问题处理
- Java 异常处理 try catch finally throws throw 的使用和解读(一)
- Java:使用 Java 开发的一个异常处理框架
- java语言异常的使用方法和处理经验
- 如何用java实现不同编码方式字符串的转换(包含异常处理、重复不终止输入、缓冲区bufferedreader的使用)
- 【POI xls Java map】使用POI处理xls 抽取出异常信息 --java1.8Group by ---map迭代 -- 设置单元格高度
- Java_基础—异常的注意事项及如何使用异常处理
- java异常处理-finally中使用return和throw语句