exceptionerror-handlingjulia

How to implement a (derived) Exception type in Julia?


I'm trying to figure out how to implement a custom Exception type for a library which I am writing in Julia.

This is what I have come up with so far, mostly by following information I have found elsewhere online.

struct LibraryException <: Exception
    message::String
end

Base.showerror(io::IO, err::LibraryException) = print(io, err.message)

This seems to be common across the few resources which I have found, however each reference diverges in one way or another. The inconsistency between each reference does not give me a high degree of confidence in the accuracy of the information.


The existing code which I have looks a bit like this.

try
    return someFunction(someargs)
catch err
    if (err isa ErrorException) && (occursin("part of expected message", sprint(showerror, err)))
        printlnOrLog(err)
        return false
    else
        rethrow(err)
    end
end

Which would be better if it was like this.

catch err
    if err isa LibraryException

Solution

  • This is correct. Once someFunction stops using throw("random string") and uses throw(LibraryException("random string")), if err isa LibraryException will work.