Uncatched exception in Kotlin, static analyzer based detection?
已回答
Hello folks,
Is there a feature in IntelliJ that we can use to analyze Kotlin code (especially http4k based server side code) to detect uncatched exceptions?
I'm more used to Swift development with Xcode and this feature is really missing for me, I would like at least a warning, if not an error when I build code with uncatched exception, or at least a static analyzer option to run manually.
请先登录再写评论。
Hello,
You're coming from Swift/Xcode, where "checked exceptions" (or their equivalent) are a more prominent feature, leading to compiler warnings or errors if you don't explicitly handle potential errors. Kotlin, like Java, primarily uses "unchecked exceptions" (subclasses of RuntimeException and Error), meaning the compiler doesn't force you to catch them. This is a deliberate design choice to reduce boilerplate in many common cases.
Best Regards
Human to Cat Translator App
I understand the difference in language mindset yes.
However I don’t really like discovering uncaught exceptions at runtime (sorry for the irregular mistake in OP).
Is there a way in IntelliJ to run some kind of analyzer to discover them in advance and evaluate what kind of handling is eventually needed?
1) You can try to write a custom rule for Detekt.
2) Wait until union errors|rich errors feature lands https://youtrack.jetbrains.com/issue/KT-68296
3) Wrap your exceptions into Result|Either types and use them like in Rust|ML langs.
```Kotlin
val result: Result<Response> = runCatching {
riskyHttpCall()
}
val response = result.getOrElse {
Response(Status.INTERNAL_SERVER_ERROR).body("Unexpected error: ${it.message}")
}
```
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/run-catching.html
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-result/
4) Use Arrow, it supports many things, including errors as values: https://arrow-kt.io/learn/typed-errors/working-with-typed-errors/ (it's kinda a functional approach to Kotlin)
We already use Arraow for our own code and Result|Either for exceptions we are aware of.
Main issue come from third party framework that may emit exceptions without documenting it (mainly because exception come from another framework they use and they didn't documented child exception that main happen).
That's why I was expecting some kind of static analyzer or build time check to help evaluating this gray area…
I'm not a big fan of discovering exceptions at production time…
I suggest you create a feature request for the KTIJ team on https://youtrack.jetbrains.com/issue/ for such mode\inspection.