Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option vs Exception in exception handling

After using F# option type for a while, I realize that it could be used for handling exceptional cases. I can use either option or Exception in the following examples:

  1. The find functions from List/Array/Seq modules raise KeyNotFoundException in uncommon cases, while corresponding tryFind counterparts return None in those situations.
  2. When I do backtracking (in solving N-queens, Sudoku, etc), whenever a branch has no solution, I can either raise an exception and catch it later or return None to match that value to backtrack. Those cases occur quite often until we find a solution.

My impression is option is a more functional approach, while Exception is more commonly-used in the .NET platform.

What are differences between option and Exception in exception handling in terms of usability, performance, etc? In which cases using a technique is better than using the other?

like image 244
pad Avatar asked Oct 31 '11 10:10

pad


People also ask

What is the difference between exception and exception handling?

Java Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program's instructions.

What are 3 basic keywords of exception handling mechanism?

Exception handling in C++ consist of three keywords: try , throw and catch : The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error.

Why is exception better than assertion?

The key differences between exceptions and assertions are: Assertions are intended to be used solely as a means of detecting programming errors, aka bugs. By contrast, an exception can indicate other kinds of error or "exceptional" condition; e.g. invalid user input, missing files, heap full and so on.


1 Answers

The CLR makes the operation of throwing and catching an exception extremely expensive. For this reason alone, you should prefer constructs like Option for reporting expected failures. If the failure is truly exceptional and nearly unrecoverable, go ahead and throw an exception. But as you note, things like backtracking during a search are unexceptional, and you will find your performance suffers greatly if you implement them with exceptions.

Because this is a property of the CLR, it doesn't really matter whether you are in F# or not. My understanding is that other runtimes for ML-like languages, e.g. ocaml, do not have this characteristic, and so may use exceptions more often for control flow.

like image 159
Sebastian Good Avatar answered Nov 11 '22 18:11

Sebastian Good