​
Slide
1
of
9

Writing a Wolfram Language Function

ERROR HANDLING
​
​
Slide
2
of
9

Learning Objectives

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

    ​
    ​
    Slide
    3
    of
    9

    Error Handling

    ​
    Slide
    4
    of
    9

    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

    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 can be used together to abort a computation if a “failure object” is received by Confirm. Recognised failure objects include Failure[…], Missing[…], $Failed, $Canceled and $Aborted.
    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 can be used to return a different result if an error message is generated during a computation (a bit like an error-specific version of If):
    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]
    ​
    Slide
    5
    of
    9

    Error Handling

    Flow Control: More Exit Options

    Throw and catch

    Throw and Catch work in a similar way to Confirm and Enclose, except the criteria for stopping a computation are more flexible. They are particularly useful for stopping loops early.
    Create a function to find the next prime after a given number:
    ​

    Break

    Break will “exit” the nearest enclosing Do, For or While loop. Unlike Throw/Catch, this will not necessarily stop the computation (unless the loop is the outermost part of the program). Although less versatile than Throw/Catch, Break can also be used to stop a loop early.
    Recreate the nextPrime function with Break and While:
    (Note that this will print an incorrect result if no prime is found.)
    ​
    ​

    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:
    ​
    ​
    Slide
    6
    of
    9

    Error Handling

    Messages

    Guide: Messages​
    ​Tech Note: Warnings and 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

    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:
    Note the different return methods used for non-string inputs. When the input is a number, the number itself is returned* (along with a message). However, if the input is anything else, the function returns unevaluated. By using False in a Condition, the dummy output will never be returned.
    *This is a fairly common approach, as is returning a failure object (such as $Failed) or nothing at all (Null).

    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:
    The global behaviour of a message can be configured with On or Off (although these are mostly for debugging purposes):
    ​
    Slide
    7
    of
    9

    Error Handling

    Optional: Testing and Debugging

    Unit testing

    Workflow: Write Unit Tests​
    Tech Note: Using the Testing Framework
    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):
    Carry out several tests at once with TestReport:
    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

    Guide: Tuning & Debugging
    Tracking down an error can be a difficult and frustrating process. Two of the simplest and most common functions used in debugging are Echo and Trace. Mathematica also has built-in debugging tools (under Evaluation ▶ Debugger), but using them goes beyond the scope of this course.
    Echo
    With up to three arguments, Echo is like a super-charged version of Print.
    Highlight negative values during a computation:
    ​
    In a similar fashion, EchoTiming will print the duration of part of an evaluation.
    Find the culprit in an unexpectedly long evaluation:
    Other EchoX functions include EchoEvaluation, EchoFunction and EchoLabel.
    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:
    ​
    ​
    Slide
    8
    of
    9

    Summary

    In this part of the course, you have covered:
    
  • Exiting on failures
  • 
  • Controlled exiting
  • 
  • Messages
  • 
  • Optional: testing and debugging
  • ​
    Slide
    9
    of
    9

    Initialisation