try keyword – Handling Errors in Julia
Keywords in Julia are words that can not be used as a variable name because they have a pre-defined meaning to the compiler.
'try' keyword in Julia is used to intercept errors thrown by the compiler, so that the program execution can continue. This helps in providing the user a warning that this code is unable to perform the specific operation but will not stop the code and continue with the execution process.
Syntax:
try
statement
catch
statement
end
‘try’ works with the ‘catch’ statement that assigns the thrown exception object to the given variable within the catch block.
Example:
# Julia program to illustrate # the use of try keyword # Creating a function to calculate# square rootfunction squareroot(x::Number) try sqrt(x) catch err if isa(err, DomainError) sqrt(complex(x)) end endend |
Output:
If we try to open a file in Write mode and it generates some error, then the catch block will catch the error and will give a warning message but the execution of code will not stop.
Example:
# Julia program to illustrate# the use of try keyword # Trying to open a filetry open("/file.txt", "w") do f println(f, "GeeksforGeeks") end # Catching errorcatch @warn "Could not write file."end |
Output:


