异常体系图
处理异常的两种方式:
1、try...catch...finally 自行处理、当有多个catch语句块时,子类异常写在写在前面,父类异常写在后面
2、throws 抛出异常、让调用者来处理、最高的处理者就是jvm , jvm处理异常的方式是打印异常信息、中断程序
编译时异常必须处理、运行时异常有默认处理机制
出现异常时: try语句块后面不再执行
public static void main(String[] args) {
try {
int a=1/0;
System.out.println(1);
}finally {
System.out.println(2);
}
System.out.println(3);
//结果: 先输出2、然后打印异常信息、中断程序
}
public static void main(String[] args) {
try {
int a=1/0;
System.out.println(1);
}catch (Exception e){
System.out.println("捕获异常进行处理");
}finally {
System.out.println(2);
}
System.out.println(3);
//结果: 先输出捕获异常进行处理、然后输出2、再输出3
}
当有多个catch语句块时:子类异常写在前面、父类异常写在后面
public static void main(String[] args) {
try {
int a=1/0;
System.out.println(1);
}catch (ArithmeticException e){
System.out.println("捕获异常进行处理");
}catch (Exception e){
System.out.println("处理");
}finally {
System.out.println(2);
}
System.out.println(3);
}
finally语句块必须执行
public static void main(String[] args) {
System.out.println(cal());
}
public static int cal(){
try {
int a=1/0;
return 1;
}catch (Exception e){
return 2;
}finally {
return 3;
}
//最后输出的结果是3
}
子类重写父类方法时: 子类异常可以等于父类异常 或者 是父类异常的子类
class A{
public void test() throws RuntimeException{
}
}
class B extends A{
@Override
public void test() throws Exception{//这里会出现错误 (子类重写父类方法时: 子类异常可以等于父类异常 或者 是父类异常的子类 )
}
}
自定义异常
自定义编译异常要基础Exception
自定义运行是异常继承RuntimeException
public class Main {
public static void main(String[] args) {
throw new CustomException("错了");
}
}
class CustomException extends RuntimeException{
public CustomException(String message) {
super(message);
}
}



