Exception handling¶
When executing programmes, various exceptions (errors) may occur which, if not handled, stop the programme execution. To avoid this and continue execution on an alternative path, you can use the try/catch operators.
The try/catch operator allows you to check exceptions and correctly handle the results that may break your programme. For example, in the code below, the function for calculating the square root usually generates an exception. By placing a try/catch block around it, you can avoid this. It is up to the developer to choose how to handle this exception, whether to log it, return a placeholder value, or, as in the case below, print an instruction. When deciding how to handle the contingency, keep in mind that using the try/catch block is much slower than using conditional branching.
try
sqrt("ten")
catch e
println("Вы должны ввести числовое значение")
end
The try/catch statements also allow you to store the exception in a variable. The following contrived example computes the square root of the second element of x if x is indexable, otherwise x is assumed to be a real number, and returns its square root:
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
Output the result of executing the sqrt_second function:
println(sqrt_second([1 4]),
"\n", sqrt_second([1 -4]),
"\n", sqrt_second(9))
In some cases, it may be necessary not only to handle an exception, but also to run some code if the try block is successfully executed. For this purpose, else may be specified after the catch block, which is run whenever no error has been thrown before:
x = []
try
x = read("file.txt", String) # для проверки работы try/catch замените название файла на любое другое
catch
println("Файл не был прочитан")
else
println(x)
end
The finally keyword provides a way to run some code regardless of how it terminates in the try block. For example, you can guarantee that an open file will be closed in the next code cell:
f = open("file.txt","w")
try
write(f, "Hello world") # измените текстовую запись и проверьте перезаписанный файл
finally
close(f)
end;