20200904-齐元朝
问题
出现异常的“山路十八弯”:
异常可以由程序猿显式书写new出来,也可以由程序运行期间虚拟机产生
不显式书写异常处理的方式,虚拟机会默认将异常从当前方法抛出,而不是结束该线程
public class Test1 {
public int d(int a,int b) {
int r=a/b;
return 0;
}
public static void main(String[] args) {
Test1 t=new Test1();
try {
t.d(100,0);
}catch(ArithmeticException a) {
System.out.println("除数不能为0");
}
System.out.println("巴啦啦能量");
}
}
运行结果如下:
![]()
说明程序运行时产生异常,并且由于d方法中没有对异常进行处理,被虚拟机从d方法抛出,并且结束d方法,抛出的异常被try……catch捕获处理,然后程序继续向下运行
只要方法抛出异常,就会结束
只要方法中的异常被捕捉,方法就可以继续运行
产生的异常会寻找处理的方案,找不到则一直抛出,直到找到处理方案或者从main方法中抛出
虽然虚拟机会将异常默认抛出,但这种方式不能是处理异常,因此当有受检查异常产生时,即使抛出,也要显式书写抛出,不能默认抛出
public class Test1 {
public int d(int a,int b) throws Exception {
if(b==0) {
throw new Exception("我就想抛出这么个异常");
}
try {
int r=a/b;
}catch(ArithmeticException w) {
System.out.println("除数不能为1");
}
System.out.println("小魔仙");
return 0;
}
public static void main(String[] args) {
Test1 t=new Test1();
try {
t.d(100,0);
}catch(ArithmeticException a) {
System.out.println("除数不能为0");
}catch(Exception e) {
System.out.println("全身变");
}
System.out.println("巴啦啦能量");
}
}
运行结果为
如果有一个受检查异常被抛出,则在本方法和 后续的调用该方法的 方法中 必须显式书写处理该异常的方案,或捕获,或抛出
如果有一个受检查异常被创建,但没有被抛出,则不必显式书写处理方案,并且,该异常不会影响程序运行
public class Test1 {
public int d(int a,int b) {
if(b==0) {
Exception e=new Exception("我就想抛出这么个异常");
}
try {
int r=a/b;
}catch(ArithmeticException w) {
System.out.println("除数不能为1");
}
System.out.println("小魔仙");
return 0;
}
public static void main(String[] args) {
Test1 t=new Test1();
try {
t.d(100,0);
}catch(ArithmeticException a) {
System.out.println("除数不能为0");
}
System.out.println("巴啦啦能量");
}
}
运行结果为:
一个异常,如果没有被抛出,则不会影响程序运行
通常,我们会将可能产生的异常显式书写 抛出或者解决 ,虚拟机会将默认产生的异常抛出,因此,会影响程序运行,我们需要处理异常
近期评论