Engee documentation
Notebook

Exception handling

When executing programs, various exceptions (errors) may occur, which, if not handled, stop the execution of the program. To avoid this and continue execution along an alternative path, you can use the try/catch operators.

The try/catch operator allows you to check for exceptions and correctly process results that may disrupt your program. For example, in the code below, the function for calculating the square root usually throws an exception. By placing a try/catch block around it, you can avoid this. The choice of how to handle this exception, whether to register it, return a placeholder value, or, as in the case below, output instructions is made by the developer. When deciding how to handle unforeseen situations, keep in mind that using the try/catch block is much slower than using conditional branching.

In [ ]:
try
    sqrt("ten")
catch e
    println("Вы должны ввести числовое значение")
end
Вы должны ввести числовое значение

The try/catch operators also allow you to save an exception in a variable. The following contrived example calculates the square root of the second element x if x is indexed, otherwise it assumes that x is a real number, and returns its square root.:

In [ ]:
sqrt_second(x) = try
           sqrt(x[2])
       catch y
           if isa(y, DomainError)
               sqrt(complex(x[2], 0))
           elseif isa(y, BoundsError)
               sqrt(x)
           end
       end
Out[0]:
sqrt_second (generic function with 1 method)

We output the result of executing the sqrt_second function:

In [ ]:
println(sqrt_second([1 4]),
        "\n", sqrt_second([1 -4]),
        "\n", sqrt_second(9))
2.0
0.0 + 2.0im
3.0

In some cases, it may be necessary not only to handle exceptions, but also to run some code if the try block is executed successfully. To do this, after the catch block, else can be specified, which runs whenever no error has been previously issued.:

In [ ]:
x = []
try
    x = read("file.txt", String) # для проверки работы try/catch замените название файла на любое другое
catch
    println("Файл не был прочитан")
else
    println(x)
end
Hello world

The keyword finally provides a way to run some code, regardless of how it ends in the try block. For example, you can ensure that an open file is closed in the next code cell.:

In [ ]:
f = open("file.txt","w")
try
    write(f, "Hello world") # измените текстовую запись и проверьте перезаписанный файл
finally
    close(f)
end;