(I was not aware of this site and asked, by mistake, a similar question on cs.stackexchange as well. It is related to this question on this site.)
Context
I'm working on a new general-purpose programming language. Exception handling is supposed to be like in Rust, but simpler. I'm specially interested in feedback for exception handling (throw, catch).
I think, same as in Swift and Rust (and Go), exception should be handled immediately, and if not, either the program must stop, or the function must throw an exception. So, no undeclared exceptions. This is what "catch
is needed, or the method needs throws
" means.
Question
- The
catch
catches all exceptions that were thrown within the scope. I argue there is no need fortry
, because try would requires (unnecessary, in my view) indentation, and messes up diffs. In Ruby, the equivalent oftry
is optional as well. Are there other languages like that? I didn't find any. Is there a problem with this idea?
Source Code Example
throw
throws an exception. catch
is needed, or the method needs throws
:
fun factorial(x int) int throws
if x > 20
throw exception('Value too large')
if x <= 1
return 1
f := factorial(x - 1)
return x * f
fun main()
i := 0
while i <= 30
println('Factorial of ' i ' is ' factorial(i))
catch e
println('Factorial of ' i ' resulted in ' e.message)
i += 1
int Foo() throws { ... }
, and a call-site sugar ofResult<int> value = try Foo() else catch;
$\endgroup$catch
is in the middle of a block - does its scope span the entire block, including after it? Does your language have the means to explicitly create a new scope? $\endgroup$if
block, and then thecatch
block is indented further than that. If you hadtry
instead ofif
then thecatch
block would be at the same level of indentation, instead of nested. As for which is the "common" case, your way is only correct if atry
statement would be the first statement in its block, which in my experience is not that common. $\endgroup$