Finding which var is an invalid type when initialising a struct

I’d check for a isa Integer, since new will still try to convert(Int, a). Additionally, ArgumentError is a little cleaner still than the generic error function and throwing explicitly also doesn’t clobber the stacktrace:

julia> struct Foo
           a::Int64
           b::Int64
           function Foo(a,b)
               a isa Integer || throw(ArgumentError("`a` is not an Integer!"))
               b isa Integer || throw(ArgumentError("`b` is not an Integer!"))
               new(a,b)
           end
       end

julia> Foo(0x0,"a")
ERROR: ArgumentError: `b` is not an Integer!
Stacktrace:
 [1] Foo(a::UInt8, b::String)
   @ Main ./REPL[2]:6
 [2] top-level scope
   @ REPL[3]:1

julia> Foo(0x0,0x1)
Foo(0, 1)

I’m still in the camp that reading a stacktrace & getting to grasps with what a MethodError means is a necessary skill when debugging julia, but yeah, giving a better error message is definitely nice.

1 Like