publicclassMain{publicstaticvoidmain(String args[]){int array[]={20,20,40};int num1 =15, num2 =10;int result =10;try{
result = num1/num2;System.out.println("The result is"+result);for(int i =5; i >=0; i--){System.out.println("The value of array is"+array[i]);}}catch(Exception e){
e.printStackTrace();}}}
结果
上面的代码示例将产生以下结果。
The result is1
java.lang.ArrayIndexOutOfBoundsException:5
at Main.main(Main.java:11)
下面是 Java 中异常打印堆栈的另一个例子。
publicclassDemo{publicstaticvoidmain(String[] args){try{ExceptionFunc();}catch(Throwable e){
e.printStackTrace();}}publicstaticvoidExceptionFunc()throwsThrowable{Throwable t =newThrowable("This is new Exception in Java...");StackTraceElement[] trace =newStackTraceElement[]{newStackTraceElement("ClassName","methodName","fileName",5)};
t.setStackTrace(trace);throw t;}}
上面的代码示例将产生以下结果。
java.lang.Throwable:This is newException in Java...
at ClassName.methodName(fileName:5)