一、JAVA异常处理的5个关键字
try:执行可能产生异常的代码
catch:捕获异常
finally:无论是否发生异常,代码总能执行
throw:手动抛出异常
throws:声明方法可能抛出的异常
二、常见的几个异常:
三、PS:
1、try-catch-finally结构中try语句块是必须的,catch、finally语句块均可选,但两者至少出现之一;
面试题:try-catch块中存在return语句,是否还执行finally块,如果执行,说出执行顺序
答:会执行,先执行finally语句,后执行return;
2、try-catch-finally块中,finally块唯一不执行的情况是在try-catch中有System.exit(1);退出程序语句。
四、引发多种类型的异常
1、排列catch语句的顺序:先子类后父类
2、发生异常时按顺序逐个匹配
3、只执行第一个与异常类型匹配的catch语句
五、声明异常
1、异常分为checked异常和运行时异常
checked异常必须捕获或者声明抛
运行时异常不要求必须捕获或声明抛出
main()方法声明的异常由JAVA虚拟机处理
throw与throws区别:
六、异常处理原则
1、异常处理与性能
2、异常只能用于非正常情况
3、不要将过于庞大的代码块放在try中
4、在catch中指定具体的异常类型
5、需要对捕获的异常做处理
作业:
1、根据编号输出课程名称,不管输入是否正确,均输出“欢迎提出建议!”语句
package com.test_19; import java.util.Scanner; public class Test2 { public static void main(String[] args) { Scanner cxj = new Scanner(System.in); System.out.print("请输入课程代号(1~3)之间数字:"); int n = cxj.nextInt(); try { switch(n) { case 1: System.out.println("C#y课程"); break; case 2: System.out.println("JAVA课程"); break; case 3: System.out.println("英语"); } }catch(Exception e) { e.printStackTrace(); System.exit(1); }finally { System.out.println("欢迎提出建议!"); } } }
测试结束:
2、使用throw抛出年龄异常
package com.test0; /** * 自定义异常年龄类 * @author Administrator * */ public class AgeErrorException extends Exception { public AgeErrorException(String mess) { super(mess); } }
package com.test0; /** * 人类 * @author Administrator * */ public class Person { private String name; private int age; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } //声明异常 public void setAge(int age) throws AgeErrorException { if(age>=1&&age<=100) { this.age = age; }else { //抛出异常 throw new AgeErrorException("年龄只能在1到100之间!"); } } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
package com.test0; /** * 测试类 * @author Administrator * */ public class Test { public static void main(String[] args) { Person p = new Person(); try { p.setAge(111); } catch (AgeErrorException e) { e.printStackTrace(); } } }
测试结果: