liveBook · Manning

Error code

As explained in Functional Programming in Scala, Second Edition

An error code is a returned value that indicates an exceptional or failed condition instead of transferring control by throwing an exception.

An error code is a returned value indicating an exceptional condition instead of transferring control by throwing an exception. It keeps failure visible in the function’s result, but callers must detect and handle it. section 4.1 section 4.2

Error codes create several practical tensions:

  • They can silently propagate when callers forget to check them, delaying failure and weakening compiler assistance. section 4.2
  • They add explicit checking and aggregation boilerplate when several functions can fail. section 4.2
  • They fit poorly with polymorphic functions when no sentinel value exists for the result type, such as an empty-sequence maximum. section 4.2
  • A typed alternative returns a generic value representing success or failure, then uses higher-order functions to centralize propagation and handling. section 4.1

An undefined mean

A mean function can throw when given an empty sequence, return a caller-supplied fallback, or represent the exceptional case explicitly. The fallback approach makes the function total but forces callers to choose a policy immediately and limits the result to Double. section 4.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains propagation risks, call-site boilerplate, polymorphic limitations, and typed alternatives without implementing the generic type.
Examples
Uses C-style return codes, failing functions, and the empty-sequence mean problem to contrast failure-handling policies.
What you can do after
Evaluate error-code designs against silent propagation, boilerplate, polymorphism, and caller-policy costs.
How it connects
Connects error codes to exceptions, higher-order functions, polymorphism, total functions, and type checking.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.