Android Kotlin Exception處理
阿新 • • 發佈:2022-01-05
Throws Exception
Kotlin 的異常和 Java 的一樣, try…catch…finally程式碼塊處理異常,唯一一點不同是:Kotlin 的異常都是 Unchecked exceptions。
checked exceptions 是必須在方法上定義並且處理的異常,比如 Java 的 IoException。
Kotlin 丟擲異常是使用 Throws 註解來實現的,如下:
@Throws(IOException::class) fun createDirectory(file: File) { if (file.exists()) throw IOException("Directory already exists") file.createNewFile() }
當我們在java程式碼中使用的時候,如下:
會提醒我們報錯,但是如果在 kotlin 檔案裡使用的時候,就不會有提示。
自定義異常
/**
* @author : zhaoyanjun
* @time : 2021/7/5
* @desc : 自定義異常
*/
class CommonException(code: Int, message: String) : Exception(message)
使用:
@Throws(CommonException::class) fun createDirectory(file: File) { if (file.exists()) throw CommonException(0, "file is exists") file.createNewFile() }
runCatching
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) kotlin.runCatching { sum(2, 4) }.onSuccess { Log.d("yy--", "結果正常$it") }.onFailure { it.printStackTrace() Log.d("yy--", "結果異常${it.message}") } } fun sum(num1: Int, num2: Int): Int { 1 / 0 return num1 + num2 } }
getOrDefault
val result = kotlin.runCatching {
sum(2, 4)
}.onSuccess {
Log.d("yy--", "結果正常$it")
}.onFailure {
it.printStackTrace()
Log.d("yy--", "結果異常${it.message}")
}.getOrDefault(100)
//如果執行正常,就返回6,執行異常就返回100
Log.d("yy--", "結果$result")
isSuccess、isFailure
val result = kotlin.runCatching {
sum(2, 4)
}.onSuccess {
Log.d("yy--", "結果正常$it")
}.onFailure {
it.printStackTrace()
Log.d("yy--", "結果異常${it.message}")
}.isFailure
exceptionOrNull
public fun exceptionOrNull(): Throwable? =
when (value) {
is Failure -> value.exception
else -> null
}
如果有異常就返回異常,否則返回 Null
getOrNull
@InlineOnly
public inline fun getOrNull(): T? =
when {
isFailure -> null
else -> value as T
}
如果失敗了,就返回null ,否則正常返回