public static void main(String args[]){ try { int n = Integer. parse. Int(args[0]); System. out. println("sum="+Sum(n)); } catch (Array. Index. Out. Of. Bounds. Exception e 1) { System. out. println(e 1. to. String()); } catch (Number. Format. Exception e 2) { System. out. println("参数<number>应为整数!"); } finally { System. out. println("程序结束!"); } } }
为了明确一个方法不捕获异常,也可在声明该方法时,使用 throws选项,抛出该类异常。格式为: [修饰符] 返回值类型 方法名[(参数表)] throws 异常类名{ …… } v public class Exception 3 { public static int Sum(int n) throws Array. Index. Out. Of. Bounds. Exception{ int s = 0; int x[ ]=new int[n]; for (int i=0; i<=n; i++) { x[i]=i; s = s +x[i]; } return s; }