Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw a specific Exception in Julia

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

Here is a link to the problem I am trying to solve: https://exercism.io/my/solutions/781af1c1f9e2448cac57c0707aced90f

(Heads up: That link may be unique to my login)

My code:

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

The test:

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

My error report, see the lines with: 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.

like image 265
shanecandoit Avatar asked Oct 08 '19 16:10

shanecandoit


1 Answers

The MethodError comes from the call to DomainError -- there are no zero-argument constructor for this exception type. From the docs:

help?> DomainError

  DomainError(val)
  DomainError(val, msg)

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

So there are one constructor which takes the value that was out of the domain, and one that, in addition, takes an extra message string. You could e.g. do

throw(DomainError(ch))

or

throw(DomainError(ch, "this character is bad"))
like image 59
fredrikekre Avatar answered Oct 30 '22 01:10

fredrikekre