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进行异常处理。

本文介绍了Java中的异常处理机制,特别是如何通过throws关键字实现强制异常处理。通过一个具体的示例,展示了如何定义可能抛出异常的方法,并在调用这些方法时如何使用try-catch块来捕获并处理这些异常。





