Java基础-异常处理机制
//什么是异常? 程序运行的过程中发生的各种错误
//为什么学习异常? 1、让程序逻辑思维更健康 2、有能力解决异常
//A异常的分类
//1 未检查异常:编译时不报错,运行时可能出错。【实质上是一些逻辑上的问题】
//2 已检查异常:编译时一定报错,且错误信息是:unhandled exception type XXX
//对待未检查异常,尽量使用逻辑思维来解决问题【if语句等】,解决不了再用异常处理机制
//对待已检查异常,必须使用异常处理机制解决
//B异常的处理机制
//1 try{...}catch{...} 处理掉;负责的表现
//2 throws 不处理,抛出;不负责分表现
public class ExceptionTest{
public static void main(){
//例一
try{
String str=null;
System.out.println(str.length());//空指针异常,即 对象不存在
}catch(NullPointerException e){
System.out.println("字符串不存在,无法计算长度");
}
//例二
String str2=null;
if(str != null){
System.out.println(str);
}else{
System.out.println("字符串不存在,无法处理业务");
}
//例三
int i=0;
if(i==0){
System.exit(0);//结束程序运行
}
double j=10/i;//ArithmeticException
System.out.println(j);
//例四
String str3="qwertyuiop";
Date d1=DateFormat.getDateInstance().parse(str3);//ParseException
}//main方法结束
//程序员转存业务本身,将异常抛出给别人处理
//一般main方法不再继续抛出给别人
public static Date StringToDate(String str) throws ParseException{
Date d1=null;
d1=DateFormat.getDateInstance().parse(str);
return d1;
}
}//类结束
//throw 人为将程序中的某种现象作为异常来看待【人造异常】
//使用方法:
//1、一般出现在方法体中(throws出现在方法头部)
//2、格式:throw new 异常类构造器([异常原因]);
//3、方法头部需要throws来配合处理这个人造异常
//如,一个人的年龄不能为负数或大于150岁,简单编码如下:
public class Student{
private int age;
public void toSetAge(int age) throws Exception{
if(age>=0&&age<=150){
this.age=age;
}else{
throw new Exception(age+"岁,不是合法的年龄");
}
}
}
//小粒度与大颗粒的异常处理机制
public class ExceptionTest{
//小粒度异常处理,颗粒a
try{
String str=null;
System.out.println(str.length());//空指针异常,即 对象不存在
}catch(NullPointerException e){
System.out.println("字符串不存在,无法计算长度");
}
//小粒度异常处理,颗粒b
try{
String str3="qwertyuiop";
Date d1=DateFormat.getDateInstance().parse(str3);//ParseException
}catch{...}
//小颗粒异常相互不影响,这不好,例如ATM取钱过程有三个颗粒
//颗粒一:插入合法的银行卡 颗粒二:输入正确的密码 颗粒三:取款
//若使用小颗粒异常处理这三个异常,这插入不合法的卡,使用不正确的密码都可以取款
//改造成大颗粒异常处理机制:结构如下
try{
颗粒一 插卡;
颗粒二 验证密码;
颗粒三 取款;
...
}catch(颗粒一的异常){
处理颗粒一的异常
}catch(颗粒二的异常){
处理颗粒二的异常
}catch(颗粒三的异常){
处理颗粒三的异常
}...
//此时,插卡错误或密码错误,就无法取款
//有时使用小颗粒比大颗粒好,如:公司有三个门窗,下班后关闭每个门窗是一个颗粒,
//若有一个门窗无法没有关闭,其它的还是应该要关闭,此时使用小粒度异常处理机制
}