Java异常处理和C#非常相似,不过Java中支持强制异常处理方式,如下:
public void testException() {
try {
this.exceptionOne(2);
} catch (ArithmeticException e) {
System.out.println(e.toString());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.toString());
}
}
public void exceptionOne(int b) throws ArithmeticException {
if (b == 1)
throw new ArithmeticException("参数异常!");
else
throw new ArrayIndexOutOfBoundsException("下标溢出!");
}
上面的exceptionOne()中使用了throws关键字,一旦方法加入了这个关键字,那么调用这个方法的类就必须加上try和catch进行异常处理。