I just had to implement the following logic:
1 - connect to DB (with potential error)
2 - run query (with potential error)
3 - return query result
4 - make sure the connection is closed
The most concise way to write this would be:
try # catch all errors here conn = db_connect(...) result = db_query(conn, ...) finally # make sure you disconnect disconnect(conn) end do_stuff_with_query_result(result)
But due to the scoping rules, you end up with something like:
conn = db_connect(...) # this will require another try - catch if you want to handle the exception result = try db_query(conn, ...) finally disconnect(conn) end do_stuff_with_query_result(result)
It seems unnecessarily complicated. Is there any other way to handle this?
Also, why isn’t a variable defined inside
try available inside
finally ? I expected that the whole
try ... end is just one scope block.
julia> try a = 2+2 finally @show a end ------ UndefVarError ------------------- Stacktrace (most recent call last)  — anonymous at <missing>:?  — macro expansion; at REPL:4 [inlined]  — macro expansion; at show.jl:218 [inlined] UndefVarError: a not defined