:PROPERTIES:
:ID: c8eaf537-45ed-4043-89cf-6bed37b2a811
:mtime: 20231018022918
:ctime: 20231018022833
:END:
#+title: Exceptions (programming)
#+filetags: :public:project:
* Definition
In programming languages, an exception is a feature which, when an exception
is encountered, program execution immediately stops. Some programming languages
allow programs to handle exceptions, meaning that execution will resume.
* Examples of Exceptions
Let us look at how different programming languages implement exceptions
** Exceptions in [[id:8952459c-5076-4e68-8a68-5f658209f39e][Ocaml]].
*** Defining a new exception in ocaml
#+BEGIN_SRC ocaml
exception Change of int
#+END_SRC
#+RESULTS:
: exception Change of int
*** Raising and handling exceptions in ocaml
#+BEGIN_SRC ocaml :exports both
try
print_endline "before the exception" ;
raise (Change 5) ;
print_endline "after the exception";
with
| Change x -> print_endline "handled the exception"
#+END_SRC
#+RESULTS:
: ()
*** Using exceptions to alter control flow
This example comes from [[id:d69438b9-c2e4-415a-9dbe-faf0fc810413][Coin Changing Problem]].
#+BEGIN_SRC ocaml
exception NoChange
let rec change till amount =
match till , amount with
| _ , 0 -> []
| [] , _ -> raise NoChange
| coin :: till , amount -> if amount < 0 then raise NoChange
else try coin :: change (coin :: till) (amount - coin)
with NoChange -> change till amount
#+END_SRC
#+RESULTS:
: <fun>
#+BEGIN_SRC ocaml
change [ 20 ; 10 ; 5 ; 2 ; 1] 17
#+END_SRC
#+RESULTS:
| 10 | 5 | 2 |
#+BEGIN_SRC ocaml
change [5 ; 2] 6
#+END_SRC
#+RESULTS:
| 2 | 2 | 2 |