How to find line where error occurred in Mathematica notebook?

后端 未结 4 1487
别跟我提以往
别跟我提以往 2021-01-30 07:35

I have a Mathematica file called myUsefulFunctions.m containing, for example, a function called mySuperUsefulFunction. Suppose I call mySuperUsefulFunction in a notebook and get

4条回答
  •  醉梦人生
    2021-01-30 08:04

    I don't know of a way to find the line in the file, which I assume was read without error.

    You can however use Trace and related functions to see where in the evaluation chain the error occurs.

    Example:

    myFunc1[x_, y_] := x[[y]]
    myFunc2[a_List, n_] := Pick[a, a, myFunc1[a, n]]
    
    myFunc2[Range@10, #1]
    
    During evaluation of In[4]:= Part::pspec: Part specification #1 is neither an integer nor a list of integers. >>
    

    With Trace:

    myFunc2[Range@10, #1] // Trace // Column
    
    {Range[10], {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}
    myFunc2[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, #1]
    Pick[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, myFunc1[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, #1]]
    {myFunc1[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, #1], {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}[[#1]], {Message[Part::pspec, #1], {MakeBoxes[Part::pspec: Part specification #1 is neither an integer nor a list of integers. >>, StandardForm], RowBox[{RowBox[{Part, ::, "pspec"}], : , "\!\(\*StyleBox[\"\\\"Part specification \\\"\",  \"MT\"]\)\!\(\*StyleBox[\!\(#1\),  \"MT\"]\)\!\(\*StyleBox[\"\\\" is neither an integer nor a list of integers.\\\"\",  \"MT\"]\) \!\(\*ButtonBox[\">>\",  ButtonStyle->\"Link\",  ButtonFrame->None,  ButtonData:>\"paclet:ref/message/General/pspec\",  ButtonNote -> \"Part::pspec\"]\)"}]}, Null}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}[[#1]]}
    

    You can see that just before Message[Part::pspec, #1] is called, which results in a long mess of formatting, we had:

    {myFunc1[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, #1], {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}[[#1]]

    This shows that myFunc1[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, #1] is called, and this causes evaluation of {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}[[#1]] which is clearly in error.

    Please see this question and its answers for a more convenient use of Trace:

    https://stackoverflow.com/q/5459735/618728

提交回复
热议问题