We have two cases. One is when you wish to "catch" the exception and continue the program. Another is we wish to "finalize". That is to execute something important before the program stop execution. We use a try block with two keywords: catch and finally. You can use both clauses or only one depending on the case.
# try block syntax
try
[executable_region]
catch
[exception_handler]
finally
[something_important]
end
# opening and closing a file
f = open("file")
try
# operate on file
finally
close(f)
end
# catching an error
x = 0
try
z= y/x
catch err
if isa(err, ZeroDivide)
println("error division by zero")
end
end
Note: In the previous example we catch the error and copy the error in variable err. Then we use function isa() to analyze the error type. We can create errors using error() function and throw() function. Most of the type we do not catch errors and we do not create error handlers in programs.
Go back: Julia Tutorial