LoginSignup
0
0

Kotlin: エラーハンドリング

Last updated at Posted at 2023-11-30

こちらの記事を参考にしました。
サンプルコード3:例外オブジェクトの活用

プログラム

try_catch.kt
fun main() {
	System.err.println("*** 開始 ***")

	try {
		val number: Int = "abc".toInt()
		println(number)
	} catch (ee: Exception) {
		println("エラーが発生しました。")
		println(ee)
		println("エラーの型: ${ee::class.qualifiedName}")
		println("エラーメッセージ: ${ee.message}")
		println("*** ee.printStackTrace() ***")
		ee.printStackTrace()
	}

	System.err.println("*** 終了 ***")
}

## コンパイル

```text:Makefile
try_catch: try_catch.kt
	kotlinc try_catch.kt -include-runtime -d try_catch.jar
clean:
	rm -f try_catch.jar
$ make
kotlinc try_catch.kt -include-runtime -d try_catch.jar

実行

実行コマンド

java -jar try_catch.jar

実行結果

$ java -jar try_catch.jar
*** 開始 ***
エラーが発生しました。
java.lang.NumberFormatException: For input string: "abc"
エラーの型: java.lang.NumberFormatException
エラーメッセージ: For input string: "abc"
*** ee.printStackTrace() ***
java.lang.NumberFormatException: For input string: "abc"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:661)
	at java.base/java.lang.Integer.parseInt(Integer.java:777)
	at Try_catchKt.main(try_catch.kt:5)
	at Try_catchKt.main(try_catch.kt)
*** 終了 ***

IntelliJ で実行

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0