getfield抛出何种异常?getproperty是否更易捕获?
关于Julia中getfield与getproperty的异常捕获问题
问题1:getfield(nothing, :a)抛出的异常
执行getfield(nothing, :a)会抛出无具体子类型的Exception实例,报错信息为:
ERROR: type Nothing has no field a
这类异常无法通过更具体的异常子类型(如KeyError、UndefVarError等)捕获,只能用最顶层的Exception类型来捕获,这也是测试中仅能通过Exception捕获的原因。
你提供的代码片段通过try/catch捕获所有Exception并返回false,其余异常重新抛出,逻辑是可行的:
match_strings = try @. getfield(match(regex, words), :match) catch e if isa(e, Exception) return false end throw(e) end
后续问题:nothing.a/getproperty是否更易捕获?
是的,使用nothing.a(本质是调用getproperty(nothing, :a))会抛出更具体的PropertyError,可以直接通过这个子类型精准捕获,无需依赖顶层的Exception。
执行getproperty(nothing, :a)的报错信息为:
ERROR: PropertyError: type Nothing has no field a
针对性捕获示例:
try nothing.a catch e if isa(e, PropertyError) # 处理属性不存在的逻辑 println("捕获到属性不存在异常") else throw(e) end end
这种方式能避免误捕获其他无关异常,比捕获泛化的Exception更精准。
内容的提问来源于stack exchange,提问作者Raumschifffan
相关产品推荐
相关产品推荐

