常见异常关系图:
Throwable的方法:
public static void main (String[] args) {
Exception e = new Exception("这里可以写错误信息" );
String message = e.getMessage();
System.out .println(message);
System.out .println(e);
e.printStackTrace();
}
Exception(异常类):
ArrayIndexOutOfBoundsException(角标越界):
public static void main (String[] args) {
int [] array = new int [4 ];
System.out .println(array[5 ]);
}
NullPointerException(空指针异常):
public static void main (String[] args) {
int [] array = new int [4 ];
array = null ;
System.out .println(array[1 ]);
}
ArithmeticException(算术异常):
public static void main (String[] args) {
System.out .println(10 /0 );
}
处理异常:
try ...catch ...finally
try 指测试异常代码
catch 指捕获异常信息
finally 指异常结束后
class TestException {
public int fun (int a, int b) {
return a / b;
}
}
public static void main (String[] args) {
TestException test = new TestException();
try {
int num = test.fun(10 , 0 );
System.out .println(num);
}catch (ArithmeticException e) {
System.out .println("你除数是0了" );
}
System.out .println("你猜猜我执行了吗?" );
}
try…catch捕获异常的流程:
函数中代码发生异常时,就产生对应异常对象,该异常对象返回给调用者
1 .调用者无法对异常进行处理,就会把异常交给上级JVM 处理,JVM 使用 默认的处理机制
2 .调用者进行了异常处理(try ...catch )返回的异常对象会跟catch 进 行匹配,匹配成功,程序继续运行,执行catch 中的语句
多catch处理异常:
注意:
1. catch 中写了Exception 来捕获异常,要放到最下面
catch 中异常由小到大
2. 异常匹配catch 的时,被匹配上时,其他catch 就不会被匹配了
public static void main (String[] args) {
int [] array = new int [4 ];
try {
array = null ;
System.out .println(array[1 ]);
System.out .println(10 /0 );
} catch (ArrayIndexOutOfBoundsException e) {
System.out .println("你越界了" );
} catch (NullPointerException e) {
System.out .println("你空指针了" );
} catch (ArithmeticException e) {
System.out .println("你除0了" );
} catch (Exception e) {
System.out .println("你写错代码了" );
}
System.out .println("你猜我执行吗?" );
}
自定义异常:
class Person {
private String name;
private int age;
public Person () {
super ();
}
public Person (String name, int age) {
super ();
this .name = name;
this .age = age;
}
public String getName () {
return name;
}
public void setName (String name) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge (int age) throws Exception {
if (age >=0 && age <=120 ) {
this .age = age;
} else {
throw new AgeOutOfBoundsException("超出范围" );
}
}
@Override
public String toString () {
return "姓名:" + name + ", 年龄:" + age;
}
}
class AgeOutOfBoundsException extends Exception {
private static final long serialVersionUID = 1 L;
public AgeOutOfBoundsException() {
super ();
}
public AgeOutOfBoundsException(String message) {
super (message);
}
}
public static void main (String[] args) {
Person person = new Person();
person.setName("dp" );
try {
person.setAge(150 );
} catch (Exception e) {
e.printStackTrace();
}
System.out .println(person);
}