Choosing Between Option and Exceptions
Use Option<T> when the absence of a value is a normal part of business logic (e.g., a lookup key might not exist). Use exceptions for truly unexpected situations that indicate program errors or unrecoverable failures.
Functions returning Option<T> force callers to explicitly handle the missing case, preventing it from being ignored. Exceptions automatically propagate up the call stack, simplifying error propagation paths.
The code on the right shows two styles of division functions: divideException throws an exception when dividing by zero, while divideOption returns None. The former is for scenarios where "division by zero is a program error," while the latter is for "division by zero is a possible normal input."
Note
The
?? operator provides a default value for None. Try using ?? to provide a default value of 0.0 for the result of divideOption.