NET 框架中的 C# 有一个方便的NotImplementedException,我可以从我打算稍后编写的代码部分中抛出它。
Julia 中是否有类似的断言?
只需使用error("unimplemented")或throw("unimplemented")。这些异常只是为了警告您某些东西尚未实现,因此您可能不想通过代码捕获或处理它们。一个ErrorException甚至ASCIIString是足够的。
在 Julia 中,创建自己的异常类型非常简单。去年,我向 Julia 添加了以下异常类型,以及一个准确显示我想要的方式的方法:
const UTF_ERR_SHORT = "invalid UTF-8 sequence starting at index <<1>> (0x<<2>> missing one or more continuation bytes)"
const UTF_ERR_CONT = "invalid UTF-8 sequence starting at index <<1>> (0x<<2>> is not a continuation byte)"
type UnicodeError <: Exception
errmsg::AbstractString ##< A UTF_ERR_ message
errpos::Int32 ##< Position of invalid character
errchr::UInt32 ##< Invalid character
end
show(io::IO, exc::UnicodeError) = print(io, replace(replace(string("UnicodeError: ",exc.errmsg),
"<<1>>",string(exc.errpos)),"<<2>>",hex(exc.errchr)))
Run Code Online (Sandbox Code Playgroud)
现在,要抛出 UnicodeError,我可以简单地执行以下操作:
throw(UnicodeError(UTF_ERR_SHORT, pos, chr))
Run Code Online (Sandbox Code Playgroud)
得到一个完全按照我想要的方式显示的异常。