Open In App
Related Articles

try keyword – Handling Errors in Julia

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
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 root
function squareroot(x::Number)
    try
        sqrt(x)
    catch err
        if isa(err, DomainError)
            sqrt(complex(x))
        end
    end
end

                    
Output: try-keyword-julia 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 file
try
    open("/file.txt", "w") do f
        println(f, "GeeksforGeeks")
    end
      
# Catching error
catch
    @warn "Could not write file."
end

                    
Output: try-keyword-julia-02

Last Updated : 22 Apr, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads