1捕获异常

1.1 finally语句保证有无错误都会执行

try{...}catch (){...}finally{...}

  • 使用try...catch捕获异常
  • 可能发生异常的语句放在try{...}中
  • 使用catch捕获对应的Exception及其子类

1.2 捕获多个异常

try{...} catch() {...} catch(){...}finally{..}

使用多个catch子句:

  • 每个catch捕获对应的Exception及其子类
  • 从上到下匹配,匹配到某个catch后不再继续匹配

注意:catch的顺序非常重要,子类必须写在前面:

try{...} catch(IOException e){...} catch(UnsupportedEncodingException e){...}

UnsupportedEncodingException是IOExcetion的子类,这样UnsupportedEncodingException永远都不会被捕获到

import java.io.*;
import java.lang.String; public class Main {
public static void main(String[] args) {
process("abc");
process("0");
}
static void process(String s) {
try{
int n = Integer.parseInt(s);
int m = 100 / n;
}catch(NumberFormatException e){
System.out.println(e);
System.out.println("Bad input");
}catch (ArithmeticException e){
System.out.println(e);
System.out.println("Bad input");
}finally {
System.out.println("end process");
}
}
}

1.3 multi-catch

如果某些异常的处理逻辑相同:

  • 不存在继承关系,必须编写多条catch子句,可以用 " | " 表示多种Exception
import java.lang.String;

public class Main {
public static void main(String[] args) {
process("abc");
process("0");
}
static void process(String s) {
try{
int n = Integer.parseInt(s);
int m = 100 / n;
}catch(NumberFormatException|ArithmeticException e){
System.out.println(e);
System.out.println("Bad input");
}finally {
System.out.println("end process");
}
}
}

2.总结

  • catch子句的匹配顺序非常重要,子类必须放在前面
  • finally子句保证有无异常都会执行
  • finally是可选的
  • catch可以匹配多个非继承关系的异常(JDK >= 1.7)

最新文章

  1. 【干货分享】流程DEMO-固定资产转移流程
  2. python之最强王者(5)——Nunber(数字)
  3. python第14天
  4. Implementation Model Editor of AVEVA in OpenSceneGraph
  5. sharepoint 弹出窗口
  6. OC 框架组织架构图
  7. 在线代码格式化,在线JSON校验格式化
  8. c语言字符串操作,及常用函数
  9. js foreach比for多出两个undefined
  10. 关于Try/Catch 代码块
  11. as3.0:文字 效果
  12. C++11的新特性lambda的小试牛刀RAII
  13. 关于“#ifdef __cplusplus”
  14. apicloud教程2 (转载)
  15. iOS开发——Xcode快捷键
  16. centos7下安装apache服务器httpd的yum方式安装
  17. Winform美化MessageBox
  18. 【NOIP2015TG】solution
  19. MongoDB分片群集的部署(用心描述,详细易懂)!!
  20. 转*SqlSever查询某个表的列名称、说明、备注、注释,类型等

热门文章

  1. Quick Noodle Physics in Blender Tutorial
  2. (13)自定意义标签和过滤器 (templatetags)
  3. hdu4990 Reading comprehension 矩阵快速幂
  4. ubuntu设置静态ip后不能上网
  5. js framework comparation
  6. Ubuntu16.04 64位编译安装Hi3520D_SDK_V1.0.4.0
  7. str的用法
  8. 自然语言处理工具hanlp自定义词汇添加图解
  9. Hystrix 使用入门
  10. 基于OLSR的路由协议实现Ad-Hoc组网