如何在Julia中引发特定异常

问题描述 投票:3回答:1

我正在Julia中进行测试驱动的开发。该测试预计将引发某些异常。如何抛出预期的异常?

我正在遍历字符串并计算特定字母的出现。除“ A”,“ C”,“ G”或“ T”之外的任何字母均应导致例外情况

正在运行Julia版本1.2.0。

我已经尝试过这些替代方法:

  • throw(DomainError())
  • throw(DomainError)
  • throw("DomainError")

我希望这些资源可以根据此资源工作: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

测试:

@testset "strand with invalid nucleotides" begin
    @test_throws DomainError count_nucleotides("AGXXACT")
end

我的错误报告,请参阅以下行:Expected and 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.

exception julia
1个回答
8
投票

MethodError来自对DomainError的调用-此异常类型没有零参数构造函数。从文档:

help?> DomainError

  DomainError(val)
  DomainError(val, msg)

  The argument val to a function or constructor is outside the valid domain.

因此,有一个构造函数采用域外的值,另外一个采用额外的消息字符串。您可以例如做

throw(DomainError(ch))

throw(DomainError(ch, "this character is bad"))
© www.soinside.com 2019 - 2024. All rights reserved.