I am doing test driven development in Julia. The test expects a certain exception to be thrown. How do I throw the expected exception?
I'm looping through a string and counting the occurrence of specific letters. Any letter than 'A','C','G',or'T' should result in an exception
Running Julia version 1.2.0.
I have tried these alternatives:
throw(DomainError())
throw(DomainError)
throw("DomainError")
I expected those to work based on this resource: https://scls.gitbooks.io/ljthw/content/_chapters/11-ex8.html
这是我要解决的问题的链接:https : //exercism.io/my/solutions/781af1c1f9e2448cac57c0707aced90f
(请注意:该链接可能对我的登录名是唯一的)
我的代码:
function count_nucleotides(strand::AbstractString)
Counts = Dict()
Counts['A'] = 0
Counts['C'] = 0
Counts['G'] = 0
Counts['T'] = 0
for ch in strand
# println(ch)
if ch=='A'
Counts['A'] += 1
# Counts['A'] = Counts['A'] + 1
elseif ch=='C'
Counts['C'] += 1
elseif ch=='G'
Counts['G'] += 1
elseif ch=='T'
Counts['T'] += 1
else
throw(DomainError())
end
end
return Counts
end
Run Code Online (Sandbox Code Playgroud)
考试:
@testset "strand with invalid nucleotides" begin
@test_throws DomainError count_nucleotides("AGXXACT")
end
Run Code Online (Sandbox Code Playgroud)
我的错误报告,请参阅以下行:Expected和Thrown。
strand with invalid nucleotides: Test Failed at /Users/username/Exercism/julia/nucleotide-count/runtests.jl:18
Expression: count_nucleotides("AGXXACT")
Expected: DomainError
Thrown: MethodError
Stacktrace:
[1] top-level scope at /Users/shane/Exercism/julia/nucleotide-count/runtests.jl:18
[2] top-level scope at /Users/juliainstall/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.2/Test/src/Test.jl:1113
[3] top-level scope at /Users/username/Exercism/julia/nucleotide-count/runtests.jl:18
Test Summary: | Fail Total
strand with invalid nucleotides | 1 1
ERROR: LoadError: Some tests did not pass: 0 passed, 1 failed, 0 errored, 0 broken.
Run Code Online (Sandbox Code Playgroud)
该MethodError
到来自呼叫DomainError
没有为这个异常类型的无参数的构造函数- 。从文档:
help?> DomainError
DomainError(val)
DomainError(val, msg)
The argument val to a function or constructor is outside the valid domain.
Run Code Online (Sandbox Code Playgroud)
因此,有一个构造函数采用域外的值,另外一个构造函数采用额外的消息字符串。你可以做
throw(DomainError(ch))
Run Code Online (Sandbox Code Playgroud)
要么
throw(DomainError(ch, "this character is bad"))
Run Code Online (Sandbox Code Playgroud)