Play Scala 6 Function-type exception handling

Source: Internet
Author: User

1. Catching exceptions gives us the opportunity to recover the program. This is the benefit of exceptional existence.

Exceptions also make the program less readable, such as an exception that introduces a context-dependent variable substitution, and the way in which an exception might occur is not type-safe (that is, it does not run as it is committed to its interface)

The main idea of functional exception handling is to not throw an exception, but instead to return a value indicating that the exception has occurred. Just like the return code in the C language.


2. Look at a "partial function": a function that has certain assumptions about the value of a parameter

def mean (xs:seq[double]): Double = if (xs.isempty) throw new ArithmeticException ("Mean of empty list") Else XS . sum/xs.length


3. Compromise solution: To be able to easily add exception handling logic, for the repair program, but also to be type-safe, to ensure the function of the function

Sealed trait Option[+a] case class Some[+a] (GET:A) extends Option[a] Case Object None extends option[nothing] def mean (Xs:seq[double]): Double = if (xs.isempty) None else Some (xs.sum/xs.length)



Play Scala 6 Function-type exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.