一.thorw的使用
- 在日常的开发中,我们往往会使用到手动抛出异常,这里就需要用到thorw关键字
- 代码示例:
/**
* @ Author: Zhangyu
* @ Date: 2020/7/27
* @ Description:
*/
public class Test {
public static void main(String[] args) {
int num=1;
try {
if (num==1){
throw new Exception();//手动抛出异常代码格式
}
System.out.println(num);
}catch (Exception e) {
System.out.println("已接住手动抛出异常");
}
}
}
输出结果:
已接住手动抛出异常
二.thorws异常
- thorws的作用是将方法或类内遇到的指定异常抛出,由上一级处理
/**
* @ Author: Zhangyu
* @ Date: 2020/7/27
* @ Description:
*/
public class Test {
public static void test()throws Exception{//将异常抛出方法,由上一级处理
throw new Exception();
}
public static void main(String[] args) {
try {
test();//处理异常
}catch (Exception e){
System.out.println("已接收方法抛出的异常!");
}
}
}
输出结果:
已接收方法抛出的异常!