Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Exception handling: 'catch' without explicit 'try'

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).

Questions:

  • The catch catches all exceptions that were thrown within the scope. I argue there is no need for try, because try would requires (unnecessary, in my view) indentation, and messes up diffs. I wonder if other programming languages have this feature? I didn't find any. Is there a problem with this idea?

  • I think one exception type is sufficient. It has the fields code (int), message (string), and optional data (payload - byte array). Do you see any obvious problem with this?

Exceptions

throw throws an exception. catch is needed, or the method needs throws. In the following example, the scope of the catch is the while loop.

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

Answer

Cancel
3
  • $\begingroup$ > "in Swift a non-throwing function isnt allowed by the compiler to call a throwing function outside a try block" ... except if the function throws itself. Which I think is the right choice! (Same as in Rust). $\endgroup$ Commented Jun 27 at 8:53
  • $\begingroup$ > Now what if the catch statement is inside an if? Then the catch statement will only catch exceptions that are thrown within the if statement. $\endgroup$ Commented Jun 27 at 8:55
  • $\begingroup$ When I read you comment (answer?) I think that you might have misunderstood my proposal. I'm planning to have the same type of exception handling as Swift, which is "catch is needed, or the method needs throws". Same as Swift. $\endgroup$ Commented Jun 27 at 8:57

-