diff --git a/src/LarvaDatasets.jl b/src/LarvaDatasets.jl
index eef36fe5d7a8856ac59e57bad724e044a0d70d7e..fdb25e8da0cca04516cf977c32132e5f02d157e1 100644
--- a/src/LarvaDatasets.jl
+++ b/src/LarvaDatasets.jl
@@ -896,7 +896,7 @@ function samplesize!(index, sample_size)
         while count < targetcount
             file = rand(keys(targetcountsperfile))
             counts = targetcountsperfile[file]
-            if counts[label] < index.maxcounts[file][label]
+            if haskey(counts, label) && counts[label] < index.maxcounts[file][label]
                 counts[label] += 1
                 count += 1
             end
@@ -904,7 +904,7 @@ function samplesize!(index, sample_size)
         while targetcount < count
             file = rand(keys(targetcountsperfile))
             counts = targetcountsperfile[file]
-            if 0 < counts[label]
+            if 0 < get(counts, label, 0)
                 counts[label] -= 1
                 count -= 1
             end