Skip to content

Disallow try and catch used together #47

@mjm918

Description

@mjm918

Summary

Using try and catch together on the same expression is semantically redundant and should emit a compiler error.

Current Behavior

The following code compiles but is meaningless:

var result: int = try safe_divide(10, 0) catch e {
    println("Division by zero caught!");
};

Expected Behavior

The compiler should emit an error:

error: `try` and `catch` cannot be used together
  --> file.naml:10:5
   |
10 |     var x = try safe_divide(10, 0) catch e { ... };
   |             ^^^ remove `try` - `catch` already handles the exception
   |
help: use either `try expr ?? default` or `expr catch e { handler }`

Valid Forms

// Form 1: Try with default (converts to option, provides fallback)
var x: int = try divide(10, 0) ?? -1;

// Form 2: Catch with handler block (for side effects/early return)
var x: int = divide(10, 0) catch e {
    println(e.message);
    return;
} ?? -1;

Rationale

  • try expr converts a throwing expression to option<T>
  • expr catch e { handler } handles the exception with a block
  • Combining them adds no semantic value - catch already handles the exception

Implementation

Add validation in the parser or type checker to detect when try wraps an expression that also has a catch block, and emit an appropriate error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions