一、异常分类
- RuntimeException 运行时异常
- CheckedException 已检查异常
二、RuntimeException运行时异常
解决办法是需要通过增加“逻辑处理来避免这些异常”
1、ArithmeticException异常:试图除以0
int i = 1/0;
System.out.println(i);
解决办法:
int a=0;
int i = 1/a;
if(a!=0) {
System.out.println(i);
}
2、NullPointerException(空指针)异常
String str = null;
System.out.println(str.length()); //空指针,调用里面任何一个函数都会报异常
解决办法:
String str = null;
if(str!=null)
System.out.println(str.length());
3、ClassCastException异常
class Animal{
}
class Dog extends Animal{
}
class Cat extends Animal{
}
public static void main(String[] args) {
Animal a = new Dog();
Cat c = (Cat)a;
}
解决办法:
Animal a = new Dog();
if(a instanceof Cat) { //判断a是否为Cat类
Cat c = (Cat)a;
}
4、ArrayIndexOutOfBoundsException异常
int[] arr = new int[5];
System.out.println(arr[5]);
解决办法:
int c = 5;
int[] arr = new int[c];
if(c<arr.length) {
System.out.println(arr[5]);
}
5、NumberFormatException异常
String str1 = "123wq";
System.out.println(Integer.parseInt(str1));
解决办法:
String str1 = "123wq"; //数字格式化异常
Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(str1);
if(m.matches()) //str匹配到数字的正则表达式才能够转化
System.out.println(Integer.parseInt(str1));
三、CheckedException已检查异常
- throws方法并不需要处理发生的异常,而是向上传递给调用它的方法处理
- 应根据异常规范在方法的首部声明该方法可能抛出的异常
- 如果一个方法抛出多个已检查异常,就必须在方法的首部列出所有的异常之间以逗号隔开
四、自定义异常
public class Test04 {
public static void main(String[] args) {
Person Pr = new Person();
Pr.setAge(-1);
}
}
class Person{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
if(age<0) {
throw new IllegalException("年龄不能为负");
}
this.age = age;
}
}
class IllegalException extends RuntimeException{
public IllegalException() {
}
public IllegalException(String msg) {
super(msg);
}
}