2016-10-18 13 views

答えて

4

:スローされた例外は、あなたのケースで(例外がキャッチされた場所までのスタックを戻し

(let [numbers [3 3 0 3] 
     results (map 
       #(try (/ 3 %) 
        (catch Exception e e)) 
        numbers)] 
    (take-while #(not (instance? Exception %)) results)) 
3

ので、それはトップレベルに上がる)、その後にresultで操作することはできません。あなたは何ができるか、手動でエラーがキャッチされたいくつかの値を置くことです:

(let [numbers [3 3 0 3] 
     results (take-while number? 
          (map #(try 
            (/ 3 %) 
            (catch Throwable ex :error)) 
           numbers))] 
    results) 
+2

ここでは、「Throwable」を「Exception」に置き換えています。通常、Java ['Error's](http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html)を控えることは良い考えではありません。 – OlegTheCat

+0

'ex' - >' _' ... – OlegTheCat

1

使用keep

(let [numbers [3 3 0 3]] 
    (keep #(try 
      (/ 3 %) 
      (catch RuntimeException _ nil)) numbers)) 
2

ここcatsライブラリのexceptionモナドを使ったアプローチです:

(ns your-project.core 
    (:require [cats.monad.exception :as e])) 

(let [numbers [3 3 0 3] 
     results (->> numbers 
        (map #(e/try-on (/ 3 %))) ; wrap division result in a try 
        (take-while e/success?) ; take values while successful 
        (mapv e/extract))]  ; unwrap the values from the trys 
    results) 

;; => [1 1] 

例外の後の値を保持する場合は、

(let [numbers [3 3 0 3] 
     results (->> numbers 
        (map #(e/try-on (/ 3 %))) 
        (filter e/success?)  ; filter all successful values 
        (mapv e/extract))] 
    results) 

;; => [1 1 1] 
関連する問題