「Android/kotlin/exception」の版間の差分
提供: 初心者エンジニアの簡易メモ
(ページの作成:「==stacktraceの方法== <pre> for (i in stackTrace.indices) { Log.i(TAG, "exception className=" + stackTrace[i].className) // クラス名を取得 Log.i(TAG, "ex...」) |
|||
| 行1: | 行1: | ||
| + | ==Exceptionのカスタム== | ||
| + | HogeException.kt | ||
| + | <pre> | ||
| + | class HogeException : Exception { | ||
| + | private val code: Int | ||
| + | |||
| + | constructor(message: String, code: Int) : super("${code} ${message}") { | ||
| + | this.code = code | ||
| + | } | ||
| + | |||
| + | companion object { | ||
| + | private const val TAG = "HogeException" | ||
| + | } | ||
| + | } | ||
| + | </pre> | ||
| + | 呼び方 | ||
| + | <pre> | ||
| + | try { | ||
| + | throw HogeException("エラー10", 10) | ||
| + | } catch (e: HogeException) { | ||
| + | Log.d(TAG, e.message) | ||
| + | } | ||
| + | </pre> | ||
| + | |||
==stacktraceの方法== | ==stacktraceの方法== | ||
<pre> | <pre> | ||
2020年3月11日 (水) 17:20時点における最新版
Exceptionのカスタム
HogeException.kt
class HogeException : Exception {
private val code: Int
constructor(message: String, code: Int) : super("${code} ${message}") {
this.code = code
}
companion object {
private const val TAG = "HogeException"
}
}
呼び方
try {
throw HogeException("エラー10", 10)
} catch (e: HogeException) {
Log.d(TAG, e.message)
}
stacktraceの方法
for (i in stackTrace.indices) {
Log.i(TAG, "exception className=" + stackTrace[i].className) // クラス名を取得
Log.i(TAG, "exception methodName=" + stackTrace[i].methodName) // メソッド名を取得
Log.i(TAG, "exception fileName=" + stackTrace[i].fileName) // ファイル名を取得
Log.i(TAG, "exception lineNumber=" + stackTrace[i].lineNumber) // 行番号を取得(nativeメソッドの場合は取得できない)
Log.i(TAG, "exception isNativeMethod=" + stackTrace[i].isNativeMethod) // nativeメソッドか判定する。
Log.i(TAG, "exception 整形=" + stackTrace[i]) // スタックトレースの情報を整形して表示
}
