'with' structure type and exception handling

74 Views Asked by At

The following code does not compile because the compiler believes that the type of the 'with' expression is (U8 | None) although as I don't see how it may happen that it's body will get to None

class Disposable
  new create() => None
  fun dispose() => None
  fun value(): U8 => 42

primitive TestWith
  fun apply(): U8  =>
    with d = Disposable do 
      d.value()
    end

But if I add the 'else' section to the 'with' - everything gets fine with types. But the compiler complains that "try expression never results in an error"

primitive TestWith
  fun apply(): U8  =>
    with d = Disposable do 
      d.value()
    else
      0
    end 

Any ideas?

1

There are 1 best solutions below

1
On

with block makes sure the object is disposed even when nested code reports error. In your case the body d.value() does not produce error. You don't need with statement in this case.

You have two options to make your code compile:

a) call dispose() directly (doesn't look elegant at all):

class Disposable
  new create() => None
  fun dispose() => None
  fun value(): U8 => 42

primitive TestWith
  fun apply(): U8  =>
    let d = Disposable
    let result = d.value()
    d.dispose() // dispose manually
    result

b) have a partial function inside with body:

class Disposable
  new create() => None
  fun dispose() => None
  fun value(): U8? => error // partial function

primitive TestWith
  fun apply(): U8  =>
    with d = Disposable do 
      d.value() // possible failure here
    end