什么是异常
异常处理机制
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {//try监控区域
System.out.println(a/b);
}catch (ArithmeticException e){//catch(想要捕获的异常类型) 捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally {//处理善后工作 无论是否有异常都会执行这一步
System.out.println("finally");
}
//finally 可以不要
//如果涉及IO流和资源相关的东西,需要关闭,则需要finally
}
}
如果没有try{}这输出红色的异常信息
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
//假设要捕获多个异常,要从小到大排列
try {//try监控区域
System.out.println(a/b);
}catch (Error e){//catch(想要捕获的异常类型) 捕获异常
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
}catch (Throwable e){
System.out.println("Throwable");
}finally {//处理善后工作 无论是否有异常都会执行这一步
System.out.println("finally");
}
//finally 可以不要
//如果涉及IO流和资源相关的东西,需要关闭,则需要finally
}
}
public class Test {
public static void main(String[] args) {
try {
new Test().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a,int b)throws ArithmeticException{
if(b==0){// throw throws
throw new ArithmeticException();//主动的抛出异常,一般在方法中使用
}
System.out.println(a/b);
}
}
如果异常在意料之中,及在try{}内,程序遇到对应异常时就会抛出异常,并继续执行程序。
自定义异常
//自定义的异常类
public class MyException extends Exception{
//传递数字>10;
private int detail;
public MyException(int a){
this.detail = a;
}
//toString:异常的打印信息
@Override
public String toString() {
return "MyException{" +
"detail=" + detail +
'}';
}
}
public class Test {
//可能会存在异常的方法
static void test(int a) throws MyException{
System.out.println("传递的参数为:"+a);
if(a>10){
throw new MyException(a);//抛出
}
System.out.println("OK");
}
public static void main(String[] args) {
try {
test(11);
} catch (MyException e) {
System.out.println("MyException=>"+e);
}
}
}
总结