Here's one option: use the value of the whole try-block. This is
particularly nice in cases where you have some substitute for `(t, data)`
(or whatever) that you'd like to use when an exception is thrown. This way
you can simply have the last statement of the catch block give the
substitute.
@async while true
t, data = try
take!(outbox)
catch e
# InvalidStateException is thrown when the channel is closed
isa(e, InvalidStateException) || rethrow(e)
break
end
println(sock, json(c(t, data)))
end
On Thursday, September 3, 2015 at 5:08:33 PM UTC-4, Spencer Russell wrote:
>
> I often find myself wanting to do an assignment inside a try...catch
> block, as in the following real-world code I'm working on to read from a
> Channel until it's closed
>
> global outbox = Channel()
> @async while true
> try
> t, data = take!(outbox)
> catch e
> # InvalidStateException is thrown when the channel is closed
> isa(e, InvalidStateException) || rethrow(e)
> break
> end
> println(sock, json(c(t, data)))
> end
>
> But the problem is that try...catch blocks introduce their own scope, so t
> and data don't exist after the exception handling. One thing I've done
> before is introducing the variables before the try block, (t = nothing;
> data = nothing) block before the try...catch, but that kills the type
> stability of the variables and doesn't feel right.
>
> Is there a more Julian idiom for this sort of thing?
>
> Thanks,
> -s
>