异常笔记
-
异常分为运行时异常,和非运行时异常
-
Error和Exception的区别:Error通常是灾难性的致命错误,是程序无法控制和处理的,当发现这些异常时,Java虚拟机(JVM)一般会选择终止线程,Exception通常情况下是可以被程序处理的,并且在程序中应该可能的去处理这些异常
异常处理机制
-
异常处理的五个关键字:
-
try
-
catch
-
finally
-
-
throws
-
异常处理分为:
-
抛出异常
-
捕获异常
-
如果我们要捕获多个异常,要把最大的异常写到最下面,从小到大异常书写
package com.chen.demo04;
public class Student {
public static void main(String[] args) {
int a=9;
int b=0;
new Student().add(a,b);
}
public void add(int a,int b){
if (b==0){
//主动抛出异常 一般用在方法中进行自己创建异常主动抛出
throw new ArithmeticException();
}
}
} -
自己处理异常
package com.chen.demo04;
public class Student {
public static void main(String[] args) {
int a=9;
int b=0;
//捕获异常处理异常
try {
new Student().add(a,b);
} catch (Exception e) {
System.out.println("程序异常");
}
}
public void add(int a,int b){
if (b==0){
throw new ArithmeticException();
}
}
}
package com.chen.demo04;
public class Student {
public static void main(String[] args) {
int a=9;
int b=0;
//在这进行处理异常
try {
new Student().add(a,b);
} catch (Exception e) {
System.out.println("程序异常");
}
}
//抛出异常到上一层
public void add(int a,int b) throws ArithmeticException{
int i = a / b;
System.out.println(i);
}
}

浙公网安备 33010602011771号