#异常抛出
package base.Exception;
public class Demo01 {
public static void main(String[] args) {
int a=0;
int b=1;
System.out.println(a/b);
//try是监控区域
//catch是异出现的时候捕获出来的结果
//finally处理善后工作,finally区可以不要(善后例如IO、资源需要关闭的情况)
try {//监控区域
System.out.println(a/b);
}catch (ArithmeticException e){//catch(想要捕获的异常类型:各种异常类型——百度)捕获异常
System.out.println("程序出现异常");
}catch(Throwable throwable){//可以捕获多个异常,但是最大的异常类型必须放在最后面捕获,否则后面的异常不会捕获到
}finally {
System.out.println("finally");
}
}
}
//快捷键:选中代码块,ctrl+alt+T哦不
#捕获异常快捷键
package base.Exception;
public class Demo02 {
public static void main(String[] args) {
int a=0;
int b=1;
try {
if (b==0){
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace();//打印错误的栈信息
} finally {
}
}
}
#主动抛出异常
package base.Exception;
public class Demo03 {
public static void main(String[] args) {
new Demo03().test(1,0);
}
//假设方法中,处理不了这个异常,需要在方法上抛出异常到更高级
private void test(int a,int b) throws ArithmeticException{//throws ArithmeticException抛出
if (b==0){
throw new ArithmeticException();//主动抛出异常
}
}
}
#抛出异常之后
以后需要对进行异常捕获,让程序继续运行,在捕获的异常里面处理
package base.Exception;
public class Demo03 {
public static void main(String[] args) {
try {
new Demo03().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();
} finally {
}
}
//假设方法中,处理不了这个异常,需要在方法上抛出异常到更高级
private void test(int a,int b) throws ArithmeticException{//throws ArithmeticException抛出
if (b==0){
throw new ArithmeticException();//主动抛出异常
}
}
}
异常的注意事项:
/*异常的五个关键词:
1.try
2.catch
3.finally
4.throw
5.throws
- */