Control Flow

Julia provides a variety of control flow constructs:

The first five control flow mechanisms are standard to high-level programming languages. Tasks are not so standard: they provide non-local control flow, making it possible to switch between temporarily-suspended computations. This is a powerful construct: both exception handling and cooperative multitasking are implemented in Julia using tasks. Everyday programming requires no direct usage of tasks, but certain problems can be solved much more easily by using tasks.

Compound Expressions

Sometimes it is convenient to have a single expression which evaluates several subexpressions in order, returning the value of the last subexpression as its value. There are two Julia constructs that accomplish this: begin blocks and ; chains. The value of both compound expression constructs is that of the last subexpression. Here’s an example of a begin block:

  1. julia> z = begin
  2. x = 1
  3. y = 2
  4. x + y
  5. end
  6. 3

Since these are fairly small, simple expressions, they could easily be placed onto a single line, which is where the ; chain syntax comes in handy:

  1. julia> z = (x = 1; y = 2; x + y)
  2. 3

This syntax is particularly useful with the terse single-line function definition form introduced in Functions. Although it is typical, there is no requirement that begin blocks be multiline or that ; chains be single-line:

  1. julia> begin x = 1; y = 2; x + y end
  2. 3
  3. julia> (x = 1;
  4. y = 2;
  5. x + y)
  6. 3

Conditional Evaluation

Conditional evaluation allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of the if-elseif-else conditional syntax:

  1. if x < y
  2. println("x is less than y")
  3. elseif x > y
  4. println("x is greater than y")
  5. else
  6. println("x is equal to y")
  7. end

If the condition expression x < y is true, then the corresponding block is evaluated; otherwise the condition expression x > y is evaluated, and if it is true, the corresponding block is evaluated; if neither expression is true, the else block is evaluated. Here it is in action:

  1. julia> function test(x, y)
  2. if x < y
  3. println("x is less than y")
  4. elseif x > y
  5. println("x is greater than y")
  6. else
  7. println("x is equal to y")
  8. end
  9. end
  10. test (generic function with 1 method)
  11. julia> test(1, 2)
  12. x is less than y
  13. julia> test(2, 1)
  14. x is greater than y
  15. julia> test(1, 1)
  16. x is equal to y

The elseif and else blocks are optional, and as many elseif blocks as desired can be used. The condition expressions in the if-elseif-else construct are evaluated until the first one evaluates to true, after which the associated block is evaluated, and no further condition expressions or blocks are evaluated.

if blocks are “leaky”, i.e. they do not introduce a local scope. This means that new variables defined inside the if clauses can be used after the if block, even if they weren’t defined before. So, we could have defined the test function above as

  1. julia> function test(x,y)
  2. if x < y
  3. relation = "less than"
  4. elseif x == y
  5. relation = "equal to"
  6. else
  7. relation = "greater than"
  8. end
  9. println("x is ", relation, " y.")
  10. end
  11. test (generic function with 1 method)
  12. julia> test(2, 1)
  13. x is greater than y.

The variable relation is declared inside the if block, but used outside. However, when depending on this behavior, make sure all possible code paths define a value for the variable. The following change to the above function results in a runtime error

  1. julia> function test(x,y)
  2. if x < y
  3. relation = "less than"
  4. elseif x == y
  5. relation = "equal to"
  6. end
  7. println("x is ", relation, " y.")
  8. end
  9. test (generic function with 1 method)
  10. julia> test(1,2)
  11. x is less than y.
  12. julia> test(2,1)
  13. ERROR: UndefVarError: relation not defined
  14. Stacktrace:
  15. [1] test(::Int64, ::Int64) at ./none:7

if blocks also return a value, which may seem unintuitive to users coming from many other languages. This value is simply the return value of the last executed statement in the branch that was chosen, so

  1. julia> x = 3
  2. 3
  3. julia> if x > 0
  4. "positive!"
  5. else
  6. "negative..."
  7. end
  8. "positive!"

Note that very short conditional statements (one-liners) are frequently expressed using Short-Circuit Evaluation in Julia, as outlined in the next section.

Unlike C, MATLAB, Perl, Python, and Ruby – but like Java, and a few other stricter, typed languages – it is an error if the value of a conditional expression is anything but true or false:

  1. julia> if 1
  2. println("true")
  3. end
  4. ERROR: TypeError: non-boolean (Int64) used in boolean context

This error indicates that the conditional was of the wrong type: Int64 rather than the required Bool.

The so-called “ternary operator”, ?:, is closely related to the if-elseif-else syntax, but is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:

  1. a ? b : c

The expression a, before the ?, is a condition expression, and the ternary operation evaluates the expression b, before the :, if the condition a is true or the expression c, after the :, if it is false. Note that the spaces around ? and : are mandatory: an expression like a?b:c is not a valid ternary expression (but a newline is acceptable after both the ? and the :).

The easiest way to understand this behavior is to see an example. In the previous example, the println call is shared by all three branches: the only real choice is which literal string to print. This could be written more concisely using the ternary operator. For the sake of clarity, let’s try a two-way version first:

  1. julia> x = 1; y = 2;
  2. julia> println(x < y ? "less than" : "not less than")
  3. less than
  4. julia> x = 1; y = 0;
  5. julia> println(x < y ? "less than" : "not less than")
  6. not less than

If the expression x < y is true, the entire ternary operator expression evaluates to the string "less than" and otherwise it evaluates to the string "not less than". The original three-way example requires chaining multiple uses of the ternary operator together:

  1. julia> test(x, y) = println(x < y ? "x is less than y" :
  2. x > y ? "x is greater than y" : "x is equal to y")
  3. test (generic function with 1 method)
  4. julia> test(1, 2)
  5. x is less than y
  6. julia> test(2, 1)
  7. x is greater than y
  8. julia> test(1, 1)
  9. x is equal to y

To facilitate chaining, the operator associates from right to left.

It is significant that like if-elseif-else, the expressions before and after the : are only evaluated if the condition expression evaluates to true or false, respectively:

  1. julia> v(x) = (println(x); x)
  2. v (generic function with 1 method)
  3. julia> 1 < 2 ? v("yes") : v("no")
  4. yes
  5. "yes"
  6. julia> 1 > 2 ? v("yes") : v("no")
  7. no
  8. "no"

Short-Circuit Evaluation

The && and || operators in Julia correspond to logical “and” and “or” operations, respectively, and are typically used for this purpose. However, they have an additional property of short-circuit evaluation: they don’t necessarily evaluate their second argument, as explained below. (There are also bitwise & and | operators that can be used as logical “and” and “or” without short-circuit behavior, but beware that & and | have higher precedence than && and || for evaluation order.)

Short-circuit evaluation is quite similar to conditional evaluation. The behavior is found in most imperative programming languages having the && and || boolean operators: in a series of boolean expressions connected by these operators, only the minimum number of expressions are evaluated as are necessary to determine the final boolean value of the entire chain. Explicitly, this means that:

  • In the expression a && b, the subexpression b is only evaluated if a evaluates to true.
  • In the expression a || b, the subexpression b is only evaluated if a evaluates to false.

The reasoning is that a && b must be false if a is false, regardless of the value of b, and likewise, the value of a || b must be true if a is true, regardless of the value of b. Both && and || associate to the right, but && has higher precedence than || does. It’s easy to experiment with this behavior:

  1. julia> t(x) = (println(x); true)
  2. t (generic function with 1 method)
  3. julia> f(x) = (println(x); false)
  4. f (generic function with 1 method)
  5. julia> t(1) && t(2)
  6. 1
  7. 2
  8. true
  9. julia> t(1) && f(2)
  10. 1
  11. 2
  12. false
  13. julia> f(1) && t(2)
  14. 1
  15. false
  16. julia> f(1) && f(2)
  17. 1
  18. false
  19. julia> t(1) || t(2)
  20. 1
  21. true
  22. julia> t(1) || f(2)
  23. 1
  24. true
  25. julia> f(1) || t(2)
  26. 1
  27. 2
  28. true
  29. julia> f(1) || f(2)
  30. 1
  31. 2
  32. false

You can easily experiment in the same way with the associativity and precedence of various combinations of && and || operators.

This behavior is frequently used in Julia to form an alternative to very short if statements. Instead of if <cond> <statement> end, one can write <cond> && <statement> (which could be read as: <cond> and then <statement>). Similarly, instead of if ! <cond> <statement> end, one can write <cond> || <statement> (which could be read as: <cond> or else <statement>).

For example, a recursive factorial routine could be defined like this:

  1. julia> function fact(n::Int)
  2. n >= 0 || error("n must be non-negative")
  3. n == 0 && return 1
  4. n * fact(n-1)
  5. end
  6. fact (generic function with 1 method)
  7. julia> fact(5)
  8. 120
  9. julia> fact(0)
  10. 1
  11. julia> fact(-1)
  12. ERROR: n must be non-negative
  13. Stacktrace:
  14. [1] error at ./error.jl:33 [inlined]
  15. [2] fact(::Int64) at ./none:2
  16. [3] top-level scope

Boolean operations without short-circuit evaluation can be done with the bitwise boolean operators introduced in Mathematical Operations and Elementary Functions: & and |. These are normal functions, which happen to support infix operator syntax, but always evaluate their arguments:

  1. julia> f(1) & t(2)
  2. 1
  3. 2
  4. false
  5. julia> t(1) | t(2)
  6. 1
  7. 2
  8. true

Just like condition expressions used in if, elseif or the ternary operator, the operands of && or || must be boolean values (true or false). Using a non-boolean value anywhere except for the last entry in a conditional chain is an error:

  1. julia> 1 && true
  2. ERROR: TypeError: non-boolean (Int64) used in boolean context

On the other hand, any type of expression can be used at the end of a conditional chain. It will be evaluated and returned depending on the preceding conditionals:

  1. julia> true && (x = (1, 2, 3))
  2. (1, 2, 3)
  3. julia> false && (x = (1, 2, 3))
  4. false

Repeated Evaluation: Loops

There are two constructs for repeated evaluation of expressions: the while loop and the for loop. Here is an example of a while loop:

  1. julia> i = 1;
  2. julia> while i <= 5
  3. println(i)
  4. global i += 1
  5. end
  6. 1
  7. 2
  8. 3
  9. 4
  10. 5

The while loop evaluates the condition expression (i <= 5 in this case), and as long it remains true, keeps also evaluating the body of the while loop. If the condition expression is false when the while loop is first reached, the body is never evaluated.

The for loop makes common repeated evaluation idioms easier to write. Since counting up and down like the above while loop does is so common, it can be expressed more concisely with a for loop:

  1. julia> for i = 1:5
  2. println(i)
  3. end
  4. 1
  5. 2
  6. 3
  7. 4
  8. 5

Here the 1:5 is a range object, representing the sequence of numbers 1, 2, 3, 4, 5. The for loop iterates through these values, assigning each one in turn to the variable i. One rather important distinction between the previous while loop form and the for loop form is the scope during which the variable is visible. If the variable i has not been introduced in another scope, in the for loop form, it is visible only inside of the for loop, and not outside/afterwards. You’ll either need a new interactive session instance or a different variable name to test this:

  1. julia> for j = 1:5
  2. println(j)
  3. end
  4. 1
  5. 2
  6. 3
  7. 4
  8. 5
  9. julia> j
  10. ERROR: UndefVarError: j not defined

See Scope of Variables for a detailed explanation of variable scope and how it works in Julia.

In general, the for loop construct can iterate over any container. In these cases, the alternative (but fully equivalent) keyword in or is typically used instead of =, since it makes the code read more clearly:

  1. julia> for i in [1,4,0]
  2. println(i)
  3. end
  4. 1
  5. 4
  6. 0
  7. julia> for s ["foo","bar","baz"]
  8. println(s)
  9. end
  10. foo
  11. bar
  12. baz

Various types of iterable containers will be introduced and discussed in later sections of the manual (see, e.g., Multi-dimensional Arrays).

It is sometimes convenient to terminate the repetition of a while before the test condition is falsified or stop iterating in a for loop before the end of the iterable object is reached. This can be accomplished with the break keyword:

  1. julia> i = 1;
  2. julia> while true
  3. println(i)
  4. if i >= 5
  5. break
  6. end
  7. global i += 1
  8. end
  9. 1
  10. 2
  11. 3
  12. 4
  13. 5
  14. julia> for j = 1:1000
  15. println(j)
  16. if j >= 5
  17. break
  18. end
  19. end
  20. 1
  21. 2
  22. 3
  23. 4
  24. 5

Without the break keyword, the above while loop would never terminate on its own, and the for loop would iterate up to 1000. These loops are both exited early by using break.

In other circumstances, it is handy to be able to stop an iteration and move on to the next one immediately. The continue keyword accomplishes this:

  1. julia> for i = 1:10
  2. if i % 3 != 0
  3. continue
  4. end
  5. println(i)
  6. end
  7. 3
  8. 6
  9. 9

This is a somewhat contrived example since we could produce the same behavior more clearly by negating the condition and placing the println call inside the if block. In realistic usage there is more code to be evaluated after the continue, and often there are multiple points from which one calls continue.

Multiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables:

  1. julia> for i = 1:2, j = 3:4
  2. println((i, j))
  3. end
  4. (1, 3)
  5. (1, 4)
  6. (2, 3)
  7. (2, 4)

With this syntax, iterables may still refer to outer loop variables; e.g. for i = 1:n, j = 1:i is valid. However a break statement inside such a loop exits the entire nest of loops, not just the inner one. Both variables (i and j) are set to their current iteration values each time the inner loop runs. Therefore, assignments to i will not be visible to subsequent iterations:

  1. julia> for i = 1:2, j = 3:4
  2. println((i, j))
  3. i = 0
  4. end
  5. (1, 3)
  6. (1, 4)
  7. (2, 3)
  8. (2, 4)

If this example were rewritten to use a for keyword for each variable, then the output would be different: the second and fourth values would contain 0.

Multiple containers can be iterated over at the same time in a single for loop using zip:

  1. julia> for (j, k) in zip([1 2 3], [4 5 6 7])
  2. println((j,k))
  3. end
  4. (1, 4)
  5. (2, 5)
  6. (3, 6)

Using zip will create an iterator that is a tuple containing the subiterators for the containers passed to it. The zip iterator will iterate over all subiterators in order, choosing the $i$th element of each subiterator in the $i$th iteration of the for loop. Once any of the subiterators run out, the for loop will stop.

Exception Handling

When an unexpected condition occurs, a function may be unable to return a reasonable value to its caller. In such cases, it may be best for the exceptional condition to either terminate the program while printing a diagnostic error message, or if the programmer has provided code to handle such exceptional circumstances then allow that code to take the appropriate action.

Built-in Exceptions

Exceptions are thrown when an unexpected condition has occurred. The built-in Exceptions listed below all interrupt the normal flow of control.

Exception
ArgumentError
BoundsError
CompositeException
DimensionMismatch
DivideError
DomainError
EOFError
ErrorException
InexactError
InitError
InterruptException
InvalidStateException
KeyError
LoadError
OutOfMemoryError
ReadOnlyMemoryError
RemoteException
MethodError
OverflowError
Meta.ParseError
SystemError
TypeError
UndefRefError
UndefVarError
StringIndexError

For example, the sqrt function throws a DomainError if applied to a negative real value:

  1. julia> sqrt(-1)
  2. ERROR: DomainError with -1.0:
  3. sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
  4. Stacktrace:
  5. [...]

You may define your own exceptions in the following way:

  1. julia> struct MyCustomException <: Exception end

The-function) throw function

Exceptions can be created explicitly with throw. For example, a function defined only for nonnegative numbers could be written to throw a DomainError if the argument is negative:

  1. julia> f(x) = x>=0 ? exp(-x) : throw(DomainError(x, "argument must be nonnegative"))
  2. f (generic function with 1 method)
  3. julia> f(1)
  4. 0.36787944117144233
  5. julia> f(-1)
  6. ERROR: DomainError with -1:
  7. argument must be nonnegative
  8. Stacktrace:
  9. [1] f(::Int64) at ./none:1

Note that DomainError without parentheses is not an exception, but a type of exception. It needs to be called to obtain an Exception object:

  1. julia> typeof(DomainError(nothing)) <: Exception
  2. true
  3. julia> typeof(DomainError) <: Exception
  4. false

Additionally, some exception types take one or more arguments that are used for error reporting:

  1. julia> throw(UndefVarError(:x))
  2. ERROR: UndefVarError: x not defined

This mechanism can be implemented easily by custom exception types following the way UndefVarError is written:

  1. julia> struct MyUndefVarError <: Exception
  2. var::Symbol
  3. end
  4. julia> Base.showerror(io::IO, e::MyUndefVarError) = print(io, e.var, " not defined")

Note

When writing an error message, it is preferred to make the first word lowercase. For example,

size(A) == size(B) || throw(DimensionMismatch("size of A not equal to size of B"))

is preferred over

size(A) == size(B) || throw(DimensionMismatch("Size of A not equal to size of B")).

However, sometimes it makes sense to keep the uppercase first letter, for instance if an argument to a function is a capital letter:

size(A,1) == size(B,2) || throw(DimensionMismatch("A has first dimension...")).

Errors

The error function is used to produce an ErrorException that interrupts the normal flow of control.

Suppose we want to stop execution immediately if the square root of a negative number is taken. To do this, we can define a fussy version of the sqrt function that raises an error if its argument is negative:

  1. julia> fussy_sqrt(x) = x >= 0 ? sqrt(x) : error("negative x not allowed")
  2. fussy_sqrt (generic function with 1 method)
  3. julia> fussy_sqrt(2)
  4. 1.4142135623730951
  5. julia> fussy_sqrt(-1)
  6. ERROR: negative x not allowed
  7. Stacktrace:
  8. [1] error at ./error.jl:33 [inlined]
  9. [2] fussy_sqrt(::Int64) at ./none:1
  10. [3] top-level scope

If fussy_sqrt is called with a negative value from another function, instead of trying to continue execution of the calling function, it returns immediately, displaying the error message in the interactive session:

  1. julia> function verbose_fussy_sqrt(x)
  2. println("before fussy_sqrt")
  3. r = fussy_sqrt(x)
  4. println("after fussy_sqrt")
  5. return r
  6. end
  7. verbose_fussy_sqrt (generic function with 1 method)
  8. julia> verbose_fussy_sqrt(2)
  9. before fussy_sqrt
  10. after fussy_sqrt
  11. 1.4142135623730951
  12. julia> verbose_fussy_sqrt(-1)
  13. before fussy_sqrt
  14. ERROR: negative x not allowed
  15. Stacktrace:
  16. [1] error at ./error.jl:33 [inlined]
  17. [2] fussy_sqrt at ./none:1 [inlined]
  18. [3] verbose_fussy_sqrt(::Int64) at ./none:3
  19. [4] top-level scope

The try/catch statement

The try/catch statement allows for Exceptions to be tested for, and for the graceful handling of things that may ordinarily break your application. For example, in the below code the function for square root would normally throw an exception. By placing a try/catch block around it we can mitigate that here. You may choose how you wish to handle this exception, whether logging it, return a placeholder value or as in the case below where we just printed out a statement. One thing to think about when deciding how to handle unexpected situations is that using a try/catch block is much slower than using conditional branching to handle those situations. Below there are more examples of handling exceptions with a try/catch block:

  1. julia> try
  2. sqrt("ten")
  3. catch e
  4. println("You should have entered a numeric value")
  5. end
  6. You should have entered a numeric value

try/catch statements also allow the Exception to be saved in a variable. The following contrived example calculates the square root of the second element of x if x is indexable, otherwise assumes x is a real number and returns its square root:

  1. julia> sqrt_second(x) = try
  2. sqrt(x[2])
  3. catch y
  4. if isa(y, DomainError)
  5. sqrt(complex(x[2], 0))
  6. elseif isa(y, BoundsError)
  7. sqrt(x)
  8. end
  9. end
  10. sqrt_second (generic function with 1 method)
  11. julia> sqrt_second([1 4])
  12. 2.0
  13. julia> sqrt_second([1 -4])
  14. 0.0 + 2.0im
  15. julia> sqrt_second(9)
  16. 3.0
  17. julia> sqrt_second(-9)
  18. ERROR: DomainError with -9.0:
  19. sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
  20. Stacktrace:
  21. [...]

Note that the symbol following catch will always be interpreted as a name for the exception, so care is needed when writing try/catch expressions on a single line. The following code will not work to return the value of x in case of an error:

  1. try bad() catch x end

Instead, use a semicolon or insert a line break after catch:

  1. try bad() catch; x end
  2. try bad()
  3. catch
  4. x
  5. end

The power of the try/catch construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions. There are situations where no error has occurred, but the ability to unwind the stack and pass a value to a higher level is desirable. Julia provides the rethrow, backtrace, catch_backtrace and Base.catch_stack functions for more advanced error handling.

finally Clauses

In code that performs state changes or uses resources like files, there is typically clean-up work (such as closing files) that needs to be done when the code is finished. Exceptions potentially complicate this task, since they can cause a block of code to exit before reaching its normal end. The finally keyword provides a way to run some code when a given block of code exits, regardless of how it exits.

For example, here is how we can guarantee that an opened file is closed:

  1. f = open("file")
  2. try
  3. # operate on file f
  4. finally
  5. close(f)
  6. end

When control leaves the try block (for example due to a return, or just finishing normally), close(f) will be executed. If the try block exits due to an exception, the exception will continue propagating. A catch block may be combined with try and finally as well. In this case the finally block will run after catch has handled the error.

Tasks (aka Coroutines)

Tasks are a control flow feature that allows computations to be suspended and resumed in a flexible manner. We mention them here only for completeness; for a full discussion see Asynchronous Programming.