반응형
자바에서 예외처리를 하기 위해서 try/catch를 사용했다면, 코틀린에서는 runCatching이 있다.
runCatching { } 블럭 내부에서 예외가 발생하면 onFailure { } 블럭으로 코드가 동작하고, 예외가 발생하지 않으면 runCatching { } 블럭 가장 마지막 값을 파라미터로 받는 onSuceess { } 블럭이 동작합니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getWeatherItem() { | |
kotlin.runCatching { | |
"returnValue" | |
}.onSuccess { | |
Log.e("TEST", "Success : $it") | |
}.onFailure { | |
Log.e("TEST", "Fail : ${it.message}") | |
} | |
// 결과 : Success : returnValue | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getWeatherItem() { | |
kotlin.runCatching { | |
"returnValue" | |
}.onSuccess { | |
Log.e("TEST", "Success : $it") | |
}.onFailure { | |
Log.e("TEST", "Fail : ${it.message}") | |
} | |
// 결과 : Fail : null | |
} |
또한, runCatching의 결과를 Result<T> 객체로 리턴받을 수 있습니다. 그리고 getOrNull() 메소드로 runCatching 결과가 Success이면 리턴 값을 얻을 수 있고, 결과가 Fail이면 null 값이 됩니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun getWeatherItem() { | |
val result = kotlin.runCatching { | |
"returnValue" | |
}.onSuccess { | |
Log.e("TEST", "Success : $it") | |
}.onFailure { | |
Log.e("TEST", "Fail : ${it.message}") | |
} | |
Log.e("TEST", "result : ${result.getOrNull()}") | |
// 결과 : Success : returnValue | |
// 결과 : result : returnValue | |
} |
반응형