Reputation: 13600
I am new to Kotlin and I have the following problem: In my project I am using a small library (JAR, no sources). In it there are few custom exception classes defined which inherit Exception
class. Some methods throw these exceptions.
In my code I bump into the problem that I don't know what exception the library code might throw so I can catch it and thus sometimes the exception goes trough the roof.
What it is the usual way to handle such situations in Kotlin?
Upvotes: 0
Views: 128
Reputation: 1570
I don't exactly know the right approach in kotlin, but you may use the following idea from scala:
Try
-
try Success(r) catch {
case NonFatal(e) => Failure(e)
}
If exception is not fatal:
case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
case _ => true
then just return Failure(e)
otherwise throw it.
How can you use it? At least you will not end up like this:
try {
...
} catch {
case _ : Throwable => ... // catch all exceptions
}
Yes, you still don't know which exceptions code may throw, but using this approach you can control the general execution flow.
But of course, it will be much better if docs list exceptions which may be thrown.
Upvotes: 1
Reputation: 596
Normaly such exceptions should be declared in the documentation of the library that you are using (either the JavaDoc, KDoc, or a website). There is no structured way to get all exceptions a function can throw, other than decompiling the code and step through it yourself. (by using the build in decompiler, that jet brains ship in IntelliJ for example)
You could also catch all exceptions, but I would always argue, that this is not a good decision in almost all cases.
Upvotes: 1