异常等级
Throwable | |
---|---|
Error | Exception |
… | … |
抛出异常
throw new 异常类型 ()在方法里提出
throws 异常类型 () 在方法上主动抛出
捕获异常
try{
方法的调用
}catch(异常类型){
}finally{
}
package com.yan.opp.demo02;
import javax.xml.soap.Text;
public class text {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a / b);
} catch (Error e) {//异常可以分层次抛出,由低到高
System.out.println("Error");
} catch (Exception e) {
System.out.println("Exception");
} catch (Throwable e) {
System.out.println("Throwable");
} finally {//可以省略
System.out.println("finally");
}
try {
Text(a,b);
} catch (Exception e) {
System.out.println("除数不能为0");
}
}
public static void Text(int c,int d) throws Exception {//假设方法上处理不了这个异常,就在方法上抛出异常
if(d==0){
throw new Exception();//主动抛出异常
}
System.out.println(c/d);
}
}
作用
在出现异常时使程序继续跑起来