Julia 在 try-catch 块中两次抛出错误

Tho*_*oth 4 julia

假设我有代码,

try
    throw(ArgumentError("hi"))
catch 
    println("something went wrong")
    throw(ArgumentError("bye"))
end
Run Code Online (Sandbox Code Playgroud)

运行此代码会产生以下输出

something went wrong
ERROR: ArgumentError: bye
Stacktrace:
 [1] top-level scope at REPL[31]:5
caused by [exception 1]
ArgumentError: hi
Stacktrace:
 [1] top-level scope at REPL[31]:2
Run Code Online (Sandbox Code Playgroud)

基本上,它同时抛出try块中的错误和块中的错误catch

我对事情应该如何工作的理解是try应该失败,然后它应该简单地输出catch块内的内容。

任何人都可以解释这里发生了什么,以及如何重写此代码以使其具有所需的功能。

谢谢。

Bog*_*ski 5

发生的事情正是你所描述的,只有抛出的异常throw(ArgumentError("bye"))超出了try-catch块。

你看到的事情是因为如果你有这样一个“由异常引起的异常”,Julia 会通过show_exception_stackbase/errorshow.jl打印出整个异常堆栈。这样你就知道catchblock中抛出的异常是tryblock中抛出的异常引起的。但这仅用于显示目的。

您可以通过包装你的代码在另一个检查这try-catch块并调查异常从内熄灭什么try- catch

julia> try
           try
               throw(ArgumentError("hi"))
           catch
               println("something went wrong")
               throw(ArgumentError("bye"))
           end
       catch e
           dump(e)
       end
something went wrong
ArgumentError
  msg: String "bye"

julia>
Run Code Online (Sandbox Code Playgroud)