📜  try 关键字 – 处理 Julia 中的错误

📅  最后修改于: 2021-11-25 04:46:53             🧑  作者: Mango

Julia 中的关键字是不能用作变量名的词,因为它们对编译器具有预定义的含义。

'try'关键字用于拦截编译器抛出的错误,以便程序继续执行。这有助于向用户警告此代码无法执行特定操作,但不会停止代码并继续执行过程。

句法:

try
    statement
catch
    statement
end

‘try’与 ‘catch’语句一起使用,该语句将抛出的异常对象分配给 catch 块中的给定变量。

例子:

# 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

输出:
尝试关键字朱莉娅

如果我们尝试以 Write 模式打开一个文件并且它产生了一些错误,那么 catch 块将捕获错误并给出警告消息,但代码的执行不会停止。
例子:

# 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

输出:
try-keyword-julia-02