美文网首页
Julia编程09:异常处理

Julia编程09:异常处理

作者: 生信探索 | 来源:发表于2024-05-27 20:47 被阅读0次

    try-catch

    try

        可能出错的程序

    catch 异常类型变量名

        异常处理程序

    finally

        无论如何最后都要执行的程序

    end

    x = [2, -2, "a"]

    for xi in x

        try

            y = sqrt(xi)

            println("√", xi, " = ", y)

        catch e

            if isa(e, DomainError)

                println("√", xi, ": 平方根函数定义域异常")

            else

                print("√", xi, ": 平方根函数其它异常")

            end

        end

    end

    ## √2 = 1.4142135623730951

    ## √-2: 平方根函数定义域异常

    ## √a: 平方根函数其它异常

    try finally

    f = open("file")

    try

        # operate on file f

    finally

        close(f)

    end

    throw

    #利用短路逻辑,如果k<0就执行后边的语句 抛出错误

    k = -1

    k > 0 || throw(ArgumentError("k must be non-negtive")

    @assert

    k = -1

    @assert k > 0 "k must be non-negtive"

    @assert(k > 0, "k must be non-negtive")

    # @assert相当于

    if k > 0

      nothing

    else

      Base.throw(Base.AssertionError("k must be non-negtive"))

    end

    error

    平方根函数,如果参数x<0,则报错"negative x not allowed"

    fussy_sqrt(x) = x >= 0 ? sqrt(x) : error("negative x not allowed")

    Julia is a high-level, dynamic programming language. Its features are well suited for numerical analysis and computational science. Distinctive aspects of Julia's design include a type system with parametric polymorphism in a dynamic programming language; with multiple dispatch as its core programming paradigm.The most significant departures of Julia from typical dynamic languages are:The core language imposes very little; Julia Base and the standard library are written in Julia itself, including primitive operations like integer arithmetic.A rich language of types for constructing and describing objects, that can also optionally be used to make type declarations.The ability to define function behavior across many combinations of argument types via multiple dispatch.Automatic generation of efficient, specialized code for different argument types.Good performance, approaching that of statically-compiled languages like C.

    相关文章

      网友评论

          本文标题:Julia编程09:异常处理

          本文链接:https://www.haomeiwen.com/subject/qechqjtx.html