Java异常的一个小知识

时间:2023-12-24 15:52:01

有以下两个代码:

package com.lk.A;

public class Test3 {
public static void main(String[] args) {
try {
int a = args.length;
int b = 42/a;
int c[] = {42};
c[42] = 42;
System.out.println("b="+b);
} catch (ArithmeticException e) {
// TODO: handle exception
System.out.println("除0异常:"+e);
} catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组越界异常:"+e);
}
}
}

  和

package com.lk.A;

public class Test4 {
public static void main(String[] args) {
try {
procedure();
int a = 1;
int b = 42/a;
System.out.println("b="+b);
} catch (ArithmeticException e) {
// TODO: handle exception
System.out.println("除0异常:"+e);
}
} private static void procedure() {
// TODO Auto-generated method stub
try {
int c[] = {42};
c[42] = 42;
} catch (ArrayIndexOutOfBoundsException e) {
// TODO: handle exception
System.out.println("数组越界异常:"+e);
} }
}

  这个运行的结果不尽相同。

第一个运行到错误的地方就要中断了,不能再继续。因为在Java中在一个try字句中如果程序发生异常则不会继续向下执行。

而第二个程序不同的是,有一个try块在方法里,如果这个方法里的try对异常进行了处理,则后面的代码是可以执行的。

附上一个小知识:

问:Java程序中发生的异常必须进行处理吗?

答:Java异常处理不是必须或者不必须的问题,而是一种程序逻辑的问题。

如果程序在某种条件下执行正常,则程序继续进行,无须处理异常。如果发生了异常,比如数据库连接不上、文件没有找到等,则说明某种条件发生了,这就需要你对这种条件进行处理。