How to Handle Exceptions in Julia
Overview
People who have struggled with severe loneliness know, oh they know
Anyone who has struggled with unknown errors while coding understands the critical importance of errors in programming…
In Julia, errors can be thrown using the error()
function or the @error
macro. As of Julia v1.63, 25 types of built-in exceptions are defined1.
Code
julia> log(1 + 2im)
0.8047189562170501 + 1.1071487177940904im
Consider, for instance, when using the logarithmic function $\log$ in a program, only real numbers should be allowed as input. However, Julia essentially provides an extension to complex numbers $\log_{\mathbb{C}}$ by default. The program running without errors is not an accomplishment. Unintended calculations can lead to unexpected problems, so if a calculation we do not want occurs, we should error out and not proceed.
Let’s create a code that restricts the domain of the original log
to real numbers $\mathbb{R}$.
error()
Function
julia> function Rlog(x)
if typeof(1 + 2im) <: Real
return log(x)
else
error(DomainError, ": Rlog allow real number only")
end
end
Rlog(1 + 2im)
ERROR: LoadError: DomainError: Rlog allow real number only
Stacktrace:
[1] error(::Type, ::String)
@ Base .\error.jl:42
[2] Rlog(x::Complex{Int64})
@ Main c:\admin\REPL.jl:7
[3] top-level scope
@ c:\admin\REPL.jl:11
in expression starting at c:\admin\REPL.jl:11
In the above Rlog
, if the input is not a real number, it is restricted to raise a DomainError
.
@error
Macro
julia> function Rlog2(x)
if typeof(1 + 2im) <: Real
return log(x)
else
@error "Rlog2 also allow Real number only"
end
end
Rlog2(1 + 2im)
┌ Error: Rlog2 also allow Real number only
└ @ Main c:\admin\REPL.jl:17
In the above Rlog2
, if the input is not a real number, it is limited to throw an error immediately.
Raise and Throw both mean to cause an error to happen, and there’s no significant difference in the big picture. Raise is a term used in Python, etc., while Throw is used in Java, etc.
Full Code
log(1 + 2im)
function Rlog(x)
if typeof(1 + 2im) <: Real
return log(x)
else
error(DomainError, ": Rlog allow real number only")
end
end
Rlog(1 + 2im)
function Rlog2(x)
if typeof(1 + 2im) <: Real
return log(x)
else
@error "Rlog2 also allow Real number only"
end
end
Rlog2(1 + 2im)
Environment
- OS: Windows
- julia: v1.6.3