如果我在Julia中遇到错误,我如何跳到代码的某个部分

时间:2016-10-04 01:15:51

标签: if-statement try-catch julia

我有一个'包装函数',它接受输入并依次运行很多函数并在结束时吐出结果。一个简单的例子

function wrapper(a,b)
    c = first_function(a,b)
    d = second_function(c)
    if typeof(d) == Int64
        e = third_function(d)
        f = fourth_function(e)    
        g = fifth_function(f)
        try 
            h = sixth_function(g)
        catch
            i = "this has failed"
        end
        i = seventh_function(h)
    else i = "this has failed"
    end

    return i
end

在我想要设置'if - else'语句或'try-catch'语句的函数列表中大约有5个不同的位置。 'else'部分和'catch'部分总是在评估相同的事情。在这个例子中,你可以通过看到else和catch语句执行i =“this failed”来看到我的意思。

有没有一种方法可以在函数代码的底部定义i =“这已失败”,只是告诉julia跳过这行'else'或'catch'部分?例如,我喜欢上面的内容:

function wrapper(a,b)
    c = first_function(a,b)
    d = second_function(c)
    if typeof(d) == Int64
        e = third_function(d)
        f = fourth_function(e)    
        g = fifth_function(f)
        try 
            h = sixth_function(g)
        catch
            <skip to line 10>
        end
        i = seventh_function(h)
    else <skip to line 10>
    end

    <line 10> i = "this has failed"
    return i
end

4 个答案:

答案 0 :(得分:3)

您可以使用this SO post中的@def宏。例如:

@def i_fail_code begin
  i = "this has failed"
end

然后你会做:

function wrapper(a,b)
    c = first_function(a,b)
    d = second_function(c)
    if typeof(d) == Int64
        e = third_function(d)
        f = fourth_function(e)    
        g = fifth_function(f)
        try 
            h = sixth_function(g)
        catch
            @i_fail_code
        end
        i = seventh_function(h)
    else @i_fail_code
    end
    return i
end

这个宏非常酷,因为即使它只是复制/粘贴其定义中的内容,它甚至会得到错误的行号(即它会将您发送到@def定义中的正确行)

答案 1 :(得分:2)

Julia通过宏内置goto支持,这可能是最简单的选择。如下所示:

function wrapper(a,b)
    c = first_function(a,b)
    d = second_function(c)
    if typeof(d) == Int64
        e = third_function(d)
        f = fourth_function(e)    
        g = fifth_function(f)
        try 
            h = sixth_function(g)
        catch
            @goto fail
        end
        i = seventh_function(h)
    else 
        @goto fail
    end
    return i
    @label fail 
    i = "this has failed"
    return i
end

答案 2 :(得分:2)

你有一些很好的文字答案来回答你的字面问题,但真正的问题是你为什么要这样做呢?这听起来像是一个非常糟糕的设计决定。基本上你是在重新发明轮子,非常糟糕!您正在尝试实施&#34;子程序&#34;方法而不是&#34;功能性&#34;办法;几十年前,子程序几乎消失了,这是有充分理由的。事实上,你的问题基本归结为&#34; GOTO for Julia&#34; should be a really big red flag

为什么不定义另一个处理你的&#34;失败代码的函数&#34;然后打电话给它?您甚至可以在内部定义失败函数包装函数;嵌套函数在julia中是完全可以接受的。 e.g。

julia> function outer()
         function inner()
           print("Hello from inner\n");
         end
         print("Hello from outer\n");
         inner();
       end
outer (generic function with 1 method)

julia> outer()
Hello from outer
Hello from inner

所以在你的情况下,你可以简单地在你的包装函数中定义一个嵌套的handle_failure()函数,并在你想要的时候调用它,并且它就是它的全部内容。

<小时/> PS:抢占典型的&#34; GOTO在现代代码中有一些合法用途&#34;评论:是的;这不是其中之一。

答案 3 :(得分:2)

另请注意,您几乎从不想在Julia中测试变量的类型 - 您应该通过多次调度来处理它。