javaSE(基础五) 异常
Throwable: 异常体系:
1)Error:错误 2)Exception:异常
Exception: 1)Checked Exception 2)Runtime Exception
Error:错误,一般由JVM生成并脱出的,不由程序猿控制
**Exception:**异常
1)编译时异常|检查时异常:编译期间出现的异常–>必须要处理,不然程序无法运行
2)运行时异常:发生在程序运行期间,可以使用增强程序的健壮性处理 -->if
常见的运行时异常:
1.NullPointException 空指针
//程序健壮性
int[] arr=null;
//1.
if(arr!=null){}
//2.
if("null".eauals(arr)){}
2.ArrayIndexOutOfBoundsException 数组索引越界异常
3.NegativeArraySizeException 数组长度负数异常
4.ClassCastException 类型转换异常
//程序健壮性使用 instanceof
5.ArithmeticException 数学异常
6.NumberFormatException 数学格式异常
常见的编译时异常:
1.FileNotFoundException 文件不存在异常
//InputStream is = new FileInputStream("D:/test.txt");
注意:
程序一旦出现异常,后面的代码无法正常执行
异常的处理方案***
-
throws 异常抛出
在方法的内部出现异常,可以抛出到方法的上面,谁调用方法谁处理,最终异常肯定需要处理,未来项目实现过程中统一抛出统一处理
-
try…catch 异常捕获
try{
可能会出现异常的代码;
}catch(Exception e){
出现异常执行的代码;
}catch(异常类型 变量名){
出现异常执行的代码;
}…
Finally{
无论try中的代码是否出现异常,都会执行的代码;
}
注意:
1)一个try后面可以跟1~n个catch
2)catch是从上到下依次判断执行
3)try中如果没有出现异常,不执行catch判断捕获
4)try中一旦出现异常,try中后面的代码不会执行
5)如果catch中捕获的异常类型比价大,应该写在最后
6)finally:当前try…catch结构执行完毕必会执行finally中的代码,这类代码主要放资源的关系//如果调用test2() 参数为5,2条打印语句会不会执行... static void test2(int i){ try{ if(i ==5){ return; } }catch(Exception e){ }finally { System.out.println("我是finally....."); //无论是否遇到return,都会执行finally中的代码 } System.out.println(i); //不会执行 } }
自定义异常:
关键字: throw 制造异常
1)一个异常类型的对象如果不通过throw关键字,就是一个普通的对象没有异常的作用和特点,当使用throw关键字制造异常,java才会把这个对象识别成异常
2)异常类型 直接或者间接的继承自Exception
3)运行时异常必须直接或者间接的继承自RuntimeException异常类: FileNotFoundException
一个程序中真是存在的一个异常,其实就是某一个异常类的对象 new 异常类();
public class ExceptionDemo05 {
public static void main(String[] args) {
/* test();
System.out.println("测试---------------");
throw new NullPointerException("空指针异常啦...");*/
User user = new User();
user.setName("zhangsan");
int age = -18;
if(age>=18 && age<=100){
user.setAge(age);
}else{
user.setAge(20);
}
System.out.println(user);
}
static void test(){
}
}
//自定义异常类
class AgeExpception extends RuntimeException{
public AgeExpception(){}
public AgeExpception(String message){
super(message);
}
}
class User{
private String name;
private int age;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age){
if(age<18 || age>100){
throw new AgeExpception(age+"不合法!!!");
}
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}