Javaexamples-exception-printstack
提供:Dev Guides
Javaの例-スタックトレースの出力
問題の説明
例外のスタックを印刷するには?
溶液
この例は、例外クラスのprintStack()メソッドを使用して、例外のスタックを印刷する方法を示しています。
public class Main{
public static void main (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の例外の印刷スタックの別の例です。
public class Demo {
public static void main(String[] args) {
try {
ExceptionFunc();
} catch(Throwable e) {
e.printStackTrace();
}
}
public static void ExceptionFunc() throws Throwable {
Throwable t = new Throwable("This is new Exception in Java...");
StackTraceElement[] trace = new StackTraceElement[] {
new StackTraceElement("ClassName","methodName","fileName",5)
};
t.setStackTrace(trace);
throw t;
}
}
上記のコードサンプルは、次の結果を生成します。
java.lang.Throwable: This is new Exception in Java...
at ClassName.methodName(fileName:5)