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