try keyword – Handling Errors in Julia
Last Updated :
22 Apr, 2020
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:
function squareroot(x::Number)
try
sqrt(x)
catch err
if isa(err, DomainError)
sqrt( complex (x))
end
end
end
|
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:
try
open ( "/file.txt" , "w" ) do f
println(f, "GeeksforGeeks" )
end
catch
@warn "Could not write file."
end
|
Output:
Share your thoughts in the comments
Please Login to comment...