异常处理——异常越界
异常处理——异常越界
代码如下:
package Day09; public class GetMsgFromExDemo {
public static void main(String[] args) {
try {
System.out.println(sum(new int[] { 1, 2, 3, 4}));
} catch (Exception ex) {
//printStackTrace方法的使用方法如下
// ex.printStackTrace();
//getMessage方法的使用方法如下
System.out.println("\n" + ex.getMessage());
System.out.println("\n" + ex.toString());
//getStackTrace方法的使用方法如下
System.out.println("\n" + "Trace info from getStackTrace method");
StackTraceElement[] stackTraceElements = ex.getStackTrace();
for (int i = 0; i < stackTraceElements.length; i++) {
System.out.println("method " + stackTraceElements[i].getMethodName());
System.out.println("ClassName " + stackTraceElements[i].getClassName());
System.out.println("LineNumber " + stackTraceElements[i].getLineNumber());
}
}
}
private static int sum(int[] is) {
int result = 0;
for (int i = 0; i <= is.length; i++) {
result += is[i];
}
return result;
}
}