After reading a lot on Exceptions, I see that the “try-catch” syntax is considered a pain by a lot of people, and that Exceptions are not as used as they could be.
To solve this, I think there is a better way to do it:
Let’s assume I have a method request.execute()
which might throw ExampleException
. It would be nice to be able to write:
if (request.execute() throws ExampleException)
doSomething()
Compared to the traditionnal try-catch:
try {
request.execute()
} catch (e: ExampleException){
doSomething()
}
I thinik my solution is better because it is 1) more concise, 2) more readable, 3) more intuitive because it uses the same syntax as other conditionnals do.
This could also shine in when
expressions:
when (str.charAt(i)) {
'a'..'z' -> ...
'A'..'Z' -> ...
throws ArrayIndexOutOfBoundsException -> ...
else ->
}
This is a lot cleaner than the same code with a try-catch, and is definitely easy to understand. From my understanding it doesn’t seem like a major modification to the language, but I’m no expert so I could be wrong.
Maybe this would even be possible with a simple extension function, but it would be nice that this was included in the standard lib.