Skip to content

Instantly share code, notes, and snippets.

@a-poor
Last active April 9, 2021 15:44
Show Gist options
  • Save a-poor/f7b298dbbf479e1f0e6f193af79e4987 to your computer and use it in GitHub Desktop.
Save a-poor/f7b298dbbf479e1f0e6f193af79e4987 to your computer and use it in GitHub Desktop.
A small macro for wrapping an expression in a `try/catch` block.
"""
@trycatch expr
Convenience macro which wraps an expression in a `try/catch` block.
If the expression throws an error, it will be printed with the
`@error` macro.
# Examples
julia> @trycatch 1 + 1
2
julia> 1 + "dog"
ERROR: MethodError: no method matching +(::Int64, ::String)
Closest candidates are:
+(::Any, ::Any, ::Any, ::Any...) at operators.jl:538
+(::T, ::T) where T<:Union{Int128, Int16, Int32, Int64, Int8, UInt128, UInt16, UInt32, UInt64, UInt8} at int.jl:86
+(::Union{Int16, Int32, Int64, Int8}, ::BigInt) at gmp.jl:531
...
Stacktrace:
[1] top-level scope at REPL[28]:1
julia> @trycatch 1 + "dog"
┌ Error: MethodError(+, (1, "dog"), 0x0000000000006cbc)
└ @ Main REPL[13]:6
"""
macro trycatch(expr)
quote
try
$expr
catch err
@error err
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment