Julia Control Flow
Control flow statements are implemented by setting one or more conditional statements in a program. When the condition is true, the designated code is executed; when the condition is false, other designated code is executed.
Julia provides a large number of control flow statements:
-
Compound expressions:begin and ;.
-
Conditional expressions:if-elseif-else and ?: (ternary operator).
-
Short-circuit evaluation:Logical operators &&(and) and ||(or), as well as chained comparisons.
-
Loops:while and for.
-
Exception handling:try-catch, error and throw.
-
Task (coroutine):Non-local control flow, see Task and concurrency.
Compound expressions
The begin ... end expression evaluates several subexpressions in order and returns the value of the last subexpression:
Example
julia
z = begin
x =
1
y =
2
x + y
end
3
Because these are very short expressions, they can simply be put on one line, which is where the ; chain comes from:
Example
julia
z =
(
x =
1
;
y =
2
;
x + y
)
3
julia
begin x =
1
;
y =
2
;
x + y
end
3
Conditional expression
A conditional expression can decide which code block to execute based on the value of a boolean expression.
The syntax of if-elseif-else is as follows:
if
Conditional expression
1
Executed when conditional expression 1 is true
elseif
Conditional expression
2
Executed when conditional expression 2 is true
else
Executed when none of the above conditions is true
end
When using the if...elseif...else statement, the following points should be noted:
- An if may be followed by zero or one else, and the else must come after all elseif branches.
- An if may be followed by zero or more elseif branches, and elseif must come before else.
- Once a condition matches successfully, the other elseif or else branches will not be tested.
- Every if block must end with end.
If the conditional expression is not of type Bool, Julia reports an error directly; this differs from C and Python (in C, nonzero means true):
Example
julia
if
1
println
(
"true"
)
end
ERROR: TypeError: non-boolean
(
Int64
)
used
in
boolean context
The following is an analysis of the if-elseif-else conditional syntax:
Example
julia
function
test
(
x, y
)
if
x
<
y
println
("x is less than y"
)
elseif
x
y
println
(
"x is greater than y"
)
else
println
(
"x is equal to y"
)
end
end
test
(
generic
function
with
1
method
)
julia
test
(
1
,
2
)
x is less than y
julia
test
(
2
,
1
)
x is greater than y
julia
test
(
1
,
1
)
x is equal to y
Note:The if block itself does not introduce a new scope; variables defined inside an if branch can also be used outside, but you must ensure all branches assign a value to that variable, otherwise an UndefVarError is reported.
Ternary Operator
The ternary operator ?: is similar to the if-elseif-else syntax:
a ? b : c
Expression a before ? is a conditional expression; if condition a is true, the ternary operator evaluates expression b before :, and if condition a is false, it executes expression c after :.
Note:? and : The spaces around it are mandatory; an expression like a?b:c is not a valid ternary expression.
Example
julia
x =
1
;
y =
2
;
julia
println
(
x
<
y
?"less than"
:
"not less than"
)
less than
Chained nesting of the ternary operator:
Example
julia
test
(
x, y
)
=
println
(
x
<
y
?"x is less than y"
:
x
y
?
"x is greater than y"
:
"x is equal to y"
)
test
(
generic
function
with
1
method
)
julia
test
(
1
,
2
)
x is less than y
Similar to if-elseif-else, the expressions before and after : are executed accordingly only when the conditional expression is true or false (lazy evaluation).
Short-circuit evaluation
In Julia, the && and || operators correspond to the logical "and" and "or" operations respectively.
- In the expression
a && b, the subexpressionbis evaluated only whenaistrueholds. - In the expression
a || b, the subexpressionbOnly whenaisfalseholds.
&& example
julia
isodd
(
3
)
&&
@warn
(
"An odd Number!"
)
┌ Warning: An odd
Number
!
└ @ Main REPL
[
5
]
:
1
julia
isodd
(
4
)
&&
@warn
(
"An odd Number!"
)
false
|| example
julia
isodd
(
3
)
||
@warn
(
"An odd Number!"
)
true
julia
isodd
(
4
)
||
@warn
(
"An odd Number!"
)
┌ Warning: An odd
Number
!
└ @ Main REPL
[
8
]
:
1
In Julia, short-circuit evaluation is often used to replace very short if statements:cond && statement read as "if cond holds, execute statement";cond || statement read as "if cond does not hold, execute statement". For example, using || to do argument checking:
Example
Recursive factorial: throw an error directly when n is negative
julia
function
fact
(
n::
Int
)
n
=
0
||
error
(
"n must be non-negative"
)
n ==
0
&&
return
1
n
fact
(
n-
1
)
end
fact
(
generic
function
with
1
method
)
julia
fact
(
5
)
120
julia
fact
(
1
)
ERROR: n must be non-negative
Stacktrace:
[
...
]
Loop statement
Loops are implemented using the two keywords while and for.
The following is a while example of a loop:
Example
julia
i =
1
;
julia
while
i
<
=
3
println
(
i
)
globali +=
1
end
1
2
3
Note:Modifying an outer global variable inside a while loop body requires adding the global keyword. Putting the code inside a function removes the need for global, which is also better style.
for Loops are more convenient to use; the above example implemented with a for loop is as follows:
Example
julia
for
i =
1
:
3
println
(
i
)
end
1
2
3
Here 1:3 is a range object representing the sequence of numbers 1, 2, 3.
The for loop variable is visible only inside the loop; after the loop ends the variable no longer exists and does not affect a same-named variable in the outer scope:
Example
julia
for
j =
1
:
3
println
(
j
)
end
1
2
3
julia
j
ERROR: UndefVarError:
`
j
`
not defined
in
`
Main
`
Generally, a for loop can be used to iterate over any container. In this case the keyword in or ∈ is more commonly used because it makes the code clearer:
Example
julia
for
i
in
[
1
,
4
,
0
]
println
(
i
)
end
1
4
0
julia
for
s ∈
[
"foo"
,
"bar"
,
"baz"
]
println
(
s
)
end
foo
bar
baz
break and continue
We may want to terminate a loop before the test condition becomes false; this can be done with the keyword break:
Example
julia
for
j =
1
:
1000
println
(
j
)
if
j
=
3
break
end
end
1
2
3
In some scenarios you need to end the current iteration immediately and jump to the next iteration; the continue keyword can be used for this:
Example
julia
for
i =
1
:
10
if
i
%
3
!
=
0
continue
end
println
(
i
)
end
3
6
9
Nested loops and Cartesian products
Multiple nested for loops can be combined into a single outer loop to create the Cartesian product of their iteration objects:
Example
julia
for
i =
1
:
2
, j =
3
:
4
println
(
(
i, j
)
)
end
(
1
,
3
)
(
1
,
4
)
(
2
,
3
)
(
2
,
4
)
In this form, the inner loop can use outer loop variables (for example for i = 1:n, j = 1:i), but a break statement exits the entire nested loop, not just the inner loop.
You can use zip to iterate over multiple containers simultaneously in a single for loop; the loop stops as soon as any one iterator is exhausted:
Example
julia
for
(
j, k
)
in
zip
(
[
1
2
3
]
,
[
4
5
6
7
]
)
println
(
(
j, k
)
)
end
(
1
,
4
)
(
2
,
5
)
(
3
,
6
)
Comprehensions
A comprehension is a concise way of processing data that builds one new data sequence from another data sequence.
The format is as follows:
Basic format
[
Expression
for
Variables
in
List
]
With a filter condition
[
Expression
for
Variables
in
List
if
Conditional
]
Example
julia
[
x^
2
for
x
in
1
:
5
]
5
-element
Vector
{
Int64
}
:
1
4
9
16
25
With an if filter condition
julia
[
x
for
x
in
1
:
10
if
x
%
2
==
0
]
5
-element
Vector
{
Int64
}
:
2
4
6
8
10
Multi-variable nesting
julia
[
(
i, j
)
for
i
in
1
:
2
, j
in
1
:
2
]
2
×
2
Matrix
{
Tuple
{
Int64
,
Int64
}
}
:
(
1
,
1
)
(
1
,
2
)
(
2
,
1
)
(
2
,
2
)
We can also specify the element type we want to generate:
Example
julia
Float32
[
x^
2
for
x
in
1
:
3
]
3
-element
Vector
{
Float32
}
:
1.0
4.0
9.0
Iterating over arrays: enumerate
Julia provides the enumerate(iter) function, which generates an index number and the value corresponding to each index:
Example
julia
a =
[
"a"
,
"b"
,
"c"
]
;
julia
for
(
index
, value
)
in
enumerate
(
a
)
println
(
"$index $value"
)
end
1
a
2
b
3
c
Exception handling
During program execution, if an unexpected condition occurs, a function may be unable to return a reasonable value to its caller. The try / catch statement makes it convenient to handle exceptional situations.
Example
julia
try
sqrt
(
"ten"
)
catch
e
println
(
"You need to enter a number"
)
end
You need to enter a number
The variable e after catch holds the caught exception object; you can use isa to determine the exception type and handle each case separately:
Example
julia
try
sqrt
(
1
)
catch
e
if
isa
(
e, DomainError
)
println
(
"Caught DomainError, cannot take the square root of a negative number"
)
else
rethrow
(
)
Other exceptions continue to propagate upward
end
end
Caught DomainError, cannot take the square root of a negative number
Note:Exception handling in Julia is much slower than conditional judgments; try/catch should only be used for genuine exceptional situations, not as regular control flow.
The finally clause
The finally keyword provides a way to run a piece of code when a code block exits, no matter how the block is exited. A typical use is to ensure that an opened file gets closed:
Example
f =
open
(
"file"
)
try
Operate on file f
finally
close
(
f
)
end
When control flow leaves the try block (for example upon a return, or normal completion), close(f) is executed. If the try block exits due to an exception, that exception continues to propagate. A catch block can be combined with try and finally, in which case the finally block runs after catch has handled the error.
Built-in exception types
Julia has many built-in exception types; common ones include:
| Exception type | Trigger scenario |
|---|---|
ArgumentError |
An invalid argument value was passed to a function |
BoundsError |
Array index out of bounds |
DivideError |
Integer division by zero |
DomainError |
Argument outside the function's domain (e.g. square root of a negative number) |
InexactError |
Type conversion loses precision |
KeyError |
The key does not exist in the dictionary |
MethodError |
No matching method to call |
TypeError |
Type mismatch (e.g. a non-boolean value used in a condition) |
UndefVarError |
Undefined variable |
The throw function
We can use throw to explicitly create an exception. For example, if a function is defined only for non-negative numbers, when the input argument is negative you can use throw to throw a DomainError:
Example
julia
f
(
x
)
= x
=
0
?
exp
(
-x
)
:
throw
(
DomainError
(
x,
"argument must be non-negative"
)
)
f
(
generic
function
with
1
method
)
julia
f
(
1
)
0.36787944117144233
julia
f
(
1
)
ERROR: DomainError with -
1
:
argument must be non-negative
Stacktrace:
[
...
]
Note that DomainError without parentheses following it is not an exception but an exception type. We need to call it to obtain an Exception object:
Example
julia
typeof
(
DomainError
(
nothing
)
)
<
: Exception
true
julia
typeof
(
DomainError
)
<
: Exception
false
The error("message") function is a shortcut for throwing an ErrorException, suitable for simple error messages:
Example
julia> error("an error occurred") ERROR: an error occurred Stacktrace: [...] [/mycode4]
Custom exception types
We can define a custom exception type following the pattern of UndefVarError:
Example
Define the exception struct, which must inherit from Exception
julia
struct MyUndefVarError
<
: Exception
var::
Symbol
end
Customize how the error is displayed
julia
Base.
showerror
(
io::
IO
, e::MyUndefVarError
)
=
(
io, e.
var
,
" not defined"
)
julia
throw
(
MyUndefVarError
(
:x
)
)
ERROR: x not defined