Jason5lee
03/22/2022, 10:20 AMclass SomeThing {
fun throwAnException(): Nothing { ... }
}
// ...
val s: SomeThing = ...
if (...)
s.throwAnException()
2.
class SomeThing {
fun anException(): Exception { ... }
}
// ...
val s: SomeThing = ...
if (...)
throw s.anException()
Sam
03/22/2022, 10:26 AMval s: SomeThing = ...
if (...)
return s.someFailureResult()
😁Stephan Schroeder
03/22/2022, 1:13 PMSomeThing
builds the exception, but doesn't contain the logic that triggers throwing it 🤔
And if SomeThing
is some kind of exception builder, why instanciate it before it's clear that an exception will be thrown. So that's why I assume SomeThing
only contains some data, you want to add to the exception message.
So maybe 3.
// data classes come with a useful toString()-method
data class SomeData(...)
// ...
val d: SomeData = ...
// or check(condition){"generate msg given data: $d"}
require(...) {"something went wrong given data: $d"}
Casey Brooks
03/22/2022, 2:52 PMcheck()
, checkNotNull()
, error()
, etc. which follow the semantics of your #1 example. Given that it returns Nothing
, the compiler is smart enough to give you smart casting, control flow analysis, etc. in response to calling s.throwAnException()
. You won’t get that with #2, and it leaves you vulnerable to someone calling s.anException()
but not actually throwing itephemient
03/22/2022, 3:33 PMkotlin.Result.getOrThrow()
, `.exceptionOrNull()`; kotlinx.coroutines.Deferred.getCompleted()
, .getCompletionExceptionOrNull()
nkiesel
03/22/2022, 8:13 PMthrowAnException()
never returns