Is the use of exceptions a bad practice in scala?

前端 未结 3 629
鱼传尺愫
鱼传尺愫 2021-02-02 11:04

I\'ve seen many times pieces of scala code using Option (for simple values) or Either[List[Error], T] for handling errors.

this gives place to code like this

         


        
3条回答
  •  遇见更好的自我
    2021-02-02 11:31

    The answer varies between what is ideal and what is practical. Ideally, avoid using exceptions. Practically, you can't live without them.

    Scala seems to favor one-liners and along those lines v2.10 has the new monad Try:

    import scala.util.Try
    
    def percentCompleted( total:Int, done:Int ): Int = Try (done * 100 / total) getOrElse 100
    
    percentCompleted( 0, 10 )    // Catches divide-by-zero and returns 100% instead
    

提交回复
热议问题