「Java」printStackTrace()関数で例外発生時のスタックトレースを出力するサンプル

2021年1月15日

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try {
//some code
}catch(Exception ee){
ee.printStackTrace();
}
try { //some code }catch(Exception ee){ ee.printStackTrace(); }
try {
//some code
}catch(Exception ee){
  ee.printStackTrace();
}

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
public class StackTraceDemo {
private static int zeroVal = 0;
public static void main(String[] args) {
int a = 5;
funcA(a);
}
static int funcA(int x) {
int result = 0;
try {
result = x / zeroVal;
} catch (Exception ee) {
ee.printStackTrace();
}
return result + 2;
}
}
package com.arkgame.study; public class StackTraceDemo { private static int zeroVal = 0; public static void main(String[] args) { int a = 5; funcA(a); } static int funcA(int x) { int result = 0; try { result = x / zeroVal; } catch (Exception ee) { ee.printStackTrace(); } return result + 2; } }
package com.arkgame.study;

public class StackTraceDemo {

      private static int zeroVal = 0;

      public static void main(String[] args) {
            int a = 5;
            funcA(a);
      }

      static int funcA(int x) {
            int result = 0;
            try {
                  result = x / zeroVal;
            } catch (Exception ee) {
                  ee.printStackTrace();
            }
            return result + 2;
      }

}

実行結果
java.lang.ArithmeticException: / by zero
at com.arkgame.study.StackTraceDemo.funcA(StackTraceDemo.java:15)
at com.arkgame.study.StackTraceDemo.main(StackTraceDemo.java:9)

Java

Posted by arkgame