一、异常介绍
基本概念
程序执行中发生的不正常情况称为“异常”(开发中的语法错误和逻辑错误不是异常)
两大类
- Error :Java虚拟机无法解决的错误 像栈溢出
- Exception :其他因为编程错误或偶然的外在因素导致的一般性问题,可以使用代码进行处理;分为两大类:运行异常和编译异常
二、异常体系图
三、五大运行异常
一、NullPointerException空指针异常
package com.ylxstudy.exception_;
/**
* @author 杨乐昕
* @version 1.0
* 空指针异常
*/
public class NullPointerException_ {
public static void main(String[] args) {
// String name = "小黄";
String name = null;
System.out.println(name.length());
/*
* 空指针异常
* Exception in thread "main" java.lang.NullPointerException
at com.ylxstudy.exception_.NullPointerException_.main(NullPointerException_.java:11)
* */
}
}
二、ArithmeticException算数运算异常
package com.ylxstudy.exception_;
/**
* @author 杨乐昕
* @version 1.0
* 数学运算异常
*/
public class ArithmeticException_ {
public static void main(String[] args) {
int n1 = 22;
int n2 = 0;
int number = n1 / n2;
System.out.println(number);
//算术异常
//Exception in thread "main" java.lang.ArithmeticException: / by zero
}
}
三、ArrayIndexOutOfBoundsException数组下标越界异常
package com.ylxstudy.exception_;
/**
* @author 杨乐昕
* @version 1.0
* 数组下标越界异常
*/
public class ArrayIndexOutOfBoundsException_ {
public static void main(String[] args) {
int[] arr={1,2,4 };
for (int i= 0;i<=arr.length;i++){
System.out.println(arr[i]);
}
//数组下标越界异常
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
}
}
四、ClassCastException类型转换异常
package com.ylxstudy.exception_;
/**
* @author 杨乐昕
* @version 1.0
* 类型转换异常
*/
public class ClassCastException_ {
public static void main(String[] args) {
A b = new B();//向上转型 b 指向 对象B
B b1 = (B)b;//将引用对象b 向下转型 为B 编译类型
C b2 = (C) b;//b事先没有先指向C对象 不能进行向下转型
//Exception in thread "main" java.lang.ClassCastException:
// com.ylxstudy.exception_.B cannot be cast to
// com.ylxstudy.exception_.C
}
}
class A{}
class B extends A{}
class C extends A{}
五、NumberFormatException数字格式不正确异常
package com.ylxstudy.exception_;
/**
* @author 杨乐昕
* @version 1.0
* 数字格式不正确异常
*/
public class NumberFormatException_ {
public static void main(String[] args) {
String name = "小黄";
int num = Integer.parseInt(name);
//小黄字符串不能转换为数字,抛出异常
//Exception in thread "main" java.lang.NumberFormatException:
// For input string: "小黄"
}
}