Writing a Wolfram Language Function
Writing a Wolfram Language Function
ERROR HANDLING
Learning Objectives
Learning Objectives
Error Handling
Error Handling
Exit a computation when there is a failure
Exit a computation manually
Add error messages to a function
Optional: learn about testing and debugging
Summary
Summary
Error Handling
Error Handling
Error Handling
Error Handling
Errors are an inevitable part of programming. They are often unexpected, bewildering and can be tricky to track down.
Flow Control: Exiting on Failures
Flow Control: Exiting on Failures
Guide: Flow Control
An important part of error handling is catching errors before they can propagate to other parts of a program.
Confirm and Enclose
Confirm and Enclose
Create a function that fails if a key is missing from an association:
ClearAll[lookup];lookup[assoc_,key_]:=Enclose[Confirm[Lookup[assoc,key]]];lookup[<|1->a,2->b,3->c|>,4]
Create a function to calculate the square root of a number (using Newton's method) that fails if the calculation takes too long:
ClearAll[newtonSqrt];newtonSqrt[num_,initialGuess_]:=Enclose[Confirm[TimeConstrained[FixedPoint[(#+num/#)/2.&,initialGuess],1]]];newtonSqrt[15129,badGuess]
While Confirm is limited to a handful of failure types, there are several other ConfirmX functions with wider capabilities, all of which are supported by Enclose: Confirm, ConfirmBy, ConfirmMatch, ConfirmQuiet and ConfirmAssert.
Create a function that returns a number only if it is positive:
ClearAll[returnPositive];returnPositive[number_]:=Enclose[ConfirmBy[number,#>=0&]];returnPositive[RandomInteger[{-10,10}]]
Returning a Failure object is not always desirable. The second argument of Enclose can be used to modify the output.
Create a custom version of StringTake that produces a failure message if the string has fewer characters than the number being taken:
ClearAll[stringTake];stringTake[string_,n_]:=Enclose[ConfirmQuiet[StringTake[string,n]],
ReleaseHold[#["HeldMessageCall"]]&
];stringTake["Good string",4]stringTake["Short string",100]Optional: Alternative solution
Optional: Additional properties
Check
Check
Check[1/2;noError,error]Check[1/0;noError,error]
However, unlike Enclose/Confirm, it does not abort the computation:
Check[1/0;Print[printedError],error]
Recreate the stringTake function, this time returning the original string if it is too short:
ClearAll[stringTake];stringTake[string_,n_]:=Check[StringTake[string,n],string];stringTake["Good string",4]stringTake["Short string",100]
Check is often used in conjunction with Quiet to quieten all messages of a certain type (more on Quiet later).
Recreate the stringTake function, this time quietening any “take” error messages, but allowing other messages to print:
ClearAll[stringTake];stringTake[string_,n_]:=Quiet[Check[StringTake[string,n],string,
StringTake::take
],StringTake::take
];stringTake["Good string",4]stringTake["Short string",100]stringTake[notAString,1]
Error Handling
Error Handling
Flow Control: More Exit Options
Flow Control: More Exit Options
Throw and catch
Throw and catch
Create a function to find the next prime after a given number:
Break
Break
Recreate the nextPrime function with Break and While:
(Note that this will print an incorrect result if no prime is found.)
Continue
Continue
Continue can be thought of as an opposite to Break. When a given criterion is met at a step inside a loop, instead of exiting the loop, Continue will “skip over” the current step and move onto the next one. Rather than a “single point” action (such as exiting a loop), Continue is better suited to performing an action several times.
Create a function that sums all of the (positive) odd integers less than or equal to a number:
Error Handling
Error Handling
Messages
Messages
A very important part of error handling is explaining to the user what has gone wrong. This is usually done with error messages (along with good documentation).
Custom messages
Custom messages
A custom message can be created using MessageName (::) and printed with Message. Information within a message can be curated with template values, where the syntax is similar to that used in StringForm:
Create a function that prints a message (unique to the input type) if the input is not a string:
*This is a fairly common approach, as is returning a failure object (such as $Failed) or nothing at all (Null).
Suppressing messages
Suppressing messages
Quiet will suppress all messages during a calculation:
However, a “suppress everything” approach is generally not a good idea. A better approach is to quiet only the messages you want to:
Error Handling
Error Handling
Optional: Testing and Debugging
Optional: Testing and Debugging
Unit testing
Unit testing
A typical way to check the behaviour of a function is simply to try many different types of input and see what happens:
A more versatile approach is to use unit tests, which, among other things, allow you to specify the sorts of outputs you are expecting (including error messages):
Display the results of the report:
Rather than running these tests programmatically (as above), they can be run in a special test notebook (File ▶ New ▶ Programmatic Notebook ▶ Testing Notebook):
While unit testing can seem a bit over the top for a single function, it can be very useful for testing several functions together (e.g. in a program or codebase).
Debugging
Debugging
Guide: Tuning & Debugging
Echo
Highlight negative values during a computation:
Find the culprit in an unexpectedly long evaluation:
Trace
Trace will list every step in an evaluation in a list.
Track down the step at which a computation gives the wrong result due to a lack of precision:
Summary
Summary
In this part of the course, you have covered:
Exiting on failures
Controlled exiting
Messages
Optional: testing and debugging
Initialisation
Initialisation