File: errors.texi

package info (click to toggle)
octave 10.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 145,388 kB
  • sloc: cpp: 335,976; ansic: 82,241; fortran: 20,963; objc: 9,402; sh: 8,756; yacc: 4,392; lex: 4,333; perl: 1,544; java: 1,366; awk: 1,259; makefile: 659; xml: 192
file content (1337 lines) | stat: -rw-r--r-- 46,100 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
@c DO NOT EDIT!  Generated automatically by munge-texi.pl.

@c Copyright (C) 1996-2025 The Octave Project Developers
@c
@c This file is part of Octave.
@c
@c Octave is free software: you can redistribute it and/or modify it
@c under the terms of the GNU General Public License as published by
@c the Free Software Foundation, either version 3 of the License, or
@c (at your option) any later version.
@c
@c Octave is distributed in the hope that it will be useful, but
@c WITHOUT ANY WARRANTY; without even the implied warranty of
@c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
@c GNU General Public License for more details.
@c
@c You should have received a copy of the GNU General Public License
@c along with Octave; see the file COPYING.  If not, see
@c <https://www.gnu.org/licenses/>.

@node Errors and Warnings
@chapter Errors and Warnings

Octave includes several functions for printing error and warning
messages.  When you write functions that need to take special action
when they encounter abnormal conditions, you should print the error
messages using the functions described in this chapter.

Since many of Octave's functions use these functions, it is also useful
to understand them, so that errors and warnings can be handled.

@menu
* Handling Errors::
* Handling Warnings::
@end menu

@node Handling Errors
@section Handling Errors

An error is something that occurs when a program is in a state where
it doesn't make sense to continue.  An example is when a function is
called with too few input arguments.  In this situation the function
should abort with an error message informing the user of the lacking
input arguments.

Since an error can occur during the evaluation of a program, it is
very convenient to be able to detect that an error occurred, so that
the error can be fixed.  This is possible with the @code{try} statement
described in @ref{The try Statement}.

@menu
* Raising Errors::
* Catching Errors::
* Recovering From Errors::
@end menu

@node Raising Errors
@subsection Raising Errors

The most common use of errors is for checking input arguments to
functions.  The following example calls the @code{error} function if
the function @code{f} is called without any input arguments.

@example
@group
function f (arg1)
  if (nargin == 0)
    error ("not enough input arguments");
  endif
endfunction
@end group
@end example

When the @code{error} function is called, it prints the given message
and returns to the Octave prompt.  This means that no code following
a call to @code{error} will be executed.

It is also possible to assign an identification string to an error.
If an error has such an ID the user can catch this error
as will be described in the next section.  To assign an ID to an error,
simply call @code{error} with two string arguments, where the first
is the identification string, and the second is the actual error.  Note
that error IDs are in the format @qcode{"NAMESPACE:ERROR-NAME"}.  The namespace
@qcode{"Octave"} is used for Octave's own errors.  Any other string is
available as a namespace for user's own errors.

@c error libinterp/corefcn/error.cc
@anchor{XREFerror}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} error (@var{msg})
@deftypefnx {} {} error (@var{template}, @dots{})
@deftypefnx {} {} error (@var{id}, @var{template}, @dots{})
@deftypefnx {} {} error (@var{errstruct})
Display an error message and stop m-file execution.

The input @var{msg} is a simple string to which the text @samp{error: } is
prepended.  The resulting message is printed on the @code{stderr} stream.
Alternatively, the first input may be a template string @var{template} which
uses the same rules as the @code{printf} family of functions (@pxref{Formatted
Output}).  Formatting is only done for single-quoted character vectors if there
are additional arguments following the template string.  If there are no
additional arguments, the template string is used literally (i.e., without
interpreting any escape sequences in single-quoted character vectors).

The optional @var{id} argument allows programmers to tag an error
with a specific identifier so that users can later retrieve it (using
@code{lasterr} or @code{lasterror}) and know the origin of the error.
The identifier must contain at least one colon character (@qcode{':'})
and must not contain any whitespace characters.  It should be a string of
the form @qcode{"NAMESPACE:ERROR-NAME"}@.  Octave's own errors use the
@qcode{"Octave"} namespace (@pxref{XREFerror_ids,,@code{error_ids}}).
For example:

@example
@group
error ("MyNameSpace:wrong-type-argument",
       "fcn_name: argument should be numeric");
@end group
@end example

Calling @code{error} also sets Octave's internal error state such that
control will return to the top level without evaluating any further
commands.  This is useful for aborting from functions or scripts.

If the error message does not end with a newline character, Octave will
print a traceback of all the function calls leading to the error.  For
example, given the following function definitions:

@example
@group
function f () g (); end
function g () h (); end
function h () nargin == 1 || error ("nargin != 1"); end
@end group
@end example

@noindent
calling the function @code{f} will result in a list of messages that
can help you to quickly find the exact location of the error:

@example
@group
f ()
error: nargin != 1
error: called from:
error:   h at line 1, column 27
error:   g at line 1, column 15
error:   f at line 1, column 15
@end group
@end example

If the error message ends in a newline character, Octave will print the
message but will not display any traceback messages as it returns
control to the top level.  For example, modifying the error message
in the previous example to end in a newline causes Octave to only print
a single message:

@example
@group
function h () nargin == 1 || error ("nargin != 1\n"); end
f ()
error: nargin != 1
@end group
@end example

A null string ("") input to @code{error} will be ignored and the code
will continue running as if the statement were a NOP@.  This is for
compatibility with @sc{matlab}.  It also makes it possible to write code
such as

@example
@group
err_msg = "";
if (CONDITION 1)
  err_msg = "CONDITION 1 found";
elseif (CONDITION2)
  err_msg = "CONDITION 2 found";
@dots{}
endif
error (err_msg);
@end group
@end example

@noindent
which will only stop execution if an error has been found.

The function may also be called with an error structure such as that returned
from @code{lasterror}.  The @var{errstruct} argument must contain fields
@code{message}, @code{identifier}, and @code{stack}.  The first two fields are
strings with the meanings discussed above.  The @code{stack} field must be a
structure or structure array with fields @code{file}, @code{name}, and
@code{line}.

Implementation Note: For compatibility with @sc{matlab}, escape
sequences in @var{template} (e.g., @qcode{"@backslashchar{}n"} =>
newline) are processed regardless of whether @var{template} has been defined
with single quotes, as long as there are two or more input arguments.  To
disable escape sequence expansion use a second backslash before the sequence
(e.g., @qcode{"@backslashchar{}@backslashchar{}n"}) or use the
@code{regexptranslate} function.
@xseealso{@ref{XREFwarning,,warning}, @ref{XREFlasterror,,lasterror}}
@end deftypefn


Since it is common to use errors when there is something wrong with
the input to a function, Octave supports functions to simplify such code.
When the @code{print_usage} function is called, it reads the help text
of the function calling @code{print_usage}, and presents a useful error.
If the help text is written in Texinfo it is possible to present an
error message that only contains the function prototypes as described
by the @code{@@deftypefn} parts of the help text.  When the help text
isn't written in Texinfo, the error message contains the entire help
message.

Consider the following function.

@example
@group
## -*- texinfo -*-
## @@deftypefn @{@} f (@@var@{arg1@})
## Function help text goes here@dots{}
## @@end deftypefn
function f (arg1)
  if (nargin == 0)
    print_usage ();
  endif
endfunction
@end group
@end example

@noindent
When it is called with no input arguments it produces the following
error.

@example
@group
f ()

@print{}  error: Invalid call to f.  Correct usage is:
@print{}
@print{}   -- f (ARG1)
@print{}
@print{}
@print{}  Additional help for built-in functions and operators is
@print{}  available in the online version of the manual.  Use the command
@print{}  'doc <topic>' to search the manual index.
@print{}
@print{}  Help and information about Octave is also available on the WWW
@print{}  at https://www.octave.org and via the help@@octave.org
@print{}  mailing list.
@end group
@end example

@c print_usage scripts/help/print_usage.m
@anchor{XREFprint_usage}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} print_usage ()
@deftypefnx {} {} print_usage (@var{name})
Print the usage message for the function @var{name}.

When called with no input arguments the @code{print_usage} function displays
the usage message of the currently executing function.
@xseealso{@ref{XREFhelp,,help}}
@end deftypefn


@c beep scripts/io/beep.m
@anchor{XREFbeep}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {} beep ()
Produce a beep from the speaker (or visual bell).

This function sends the alarm character @qcode{"@backslashchar{}a"} to
the terminal.  Depending on the user's configuration this may produce an
audible beep, a visual bell, or nothing at all.
@xseealso{@ref{XREFputs,,puts}, @ref{XREFfputs,,fputs}, @ref{XREFprintf,,printf}, @ref{XREFfprintf,,fprintf}}
@end deftypefn


@c beep_on_error libinterp/corefcn/error.cc
@anchor{XREFbeep_on_error}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{val} =} beep_on_error ()
@deftypefnx {} {@var{old_val} =} beep_on_error (@var{new_val})
@deftypefnx {} {@var{old_val} =} beep_on_error (@var{new_val}, "local")
Query or set the internal variable that controls whether Octave will try
to ring the terminal bell before printing an error message.

When called from inside a function with the @qcode{"local"} option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
@end deftypefn


@node Catching Errors
@subsection Catching Errors

When an error occurs, it can be detected and handled using the
@code{try} statement as described in @ref{The try Statement}.
As an example, the following piece of code counts the number of errors
that occurs during a @code{for} loop.

@example
@group
number_of_errors = 0;
for n = 1:100
  try
    @dots{}
  catch
    number_of_errors++;
  end_try_catch
endfor
@end group
@end example

The above example treats all errors the same.  In many situations it
can however be necessary to discriminate between errors, and take
different actions depending on the error.  The @code{lasterror}
function returns a structure containing information about the last
error that occurred.  As an example, the code above could be changed
to count the number of errors related to the @samp{*} operator.

@example
@group
number_of_errors = 0;
for n = 1:100
  try
    @dots{}
  catch
    msg = lasterror.message;
    if (strfind (msg, "operator *"))
      number_of_errors++;
    endif
  end_try_catch
endfor
@end group
@end example

@noindent
Alternatively, the output of the @code{lasterror} function can be found
in a variable indicated immediately after the @code{catch} keyword, as
in the example below showing how to redirect an error as a warning:

@example
@group
try
  @dots{}
catch err
  warning(err.identifier, err.message);
  @dots{}
end_try_catch
@end group
@end example

@c lasterror libinterp/corefcn/error.cc
@anchor{XREFlasterror}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{lasterr} =} lasterror ()
@deftypefnx {} {} lasterror (@var{err})
@deftypefnx {} {} lasterror ("reset")
Query or set the last error message structure.

When called without arguments, return a structure containing the last error
message and other information related to this error.  The elements of the
structure are:

@table @code
@item message
The text of the last error message

@item identifier
The message identifier of this error message

@item stack
A structure containing information on where the message occurred.  This may
be an empty structure if the information cannot be obtained.  The fields of
the structure are:

@table @code
@item file
The name of the file where the error occurred

@item name
The name of function in which the error occurred

@item line
The line number at which the error occurred

@item column
An optional field with the column number at which the error occurred
@end table
@end table

The last error structure may be set by passing a scalar structure,
@var{err}, as input.  Any fields of @var{err} that match those above are
set while any unspecified fields are initialized with default values.

If @code{lasterror} is called with the argument @qcode{"reset"}, all
fields are set to their default values.
@xseealso{@ref{XREFlasterr,,lasterr}, @ref{XREFerror,,error}, @ref{XREFlastwarn,,lastwarn}}
@end deftypefn


@c lasterr libinterp/corefcn/error.cc
@anchor{XREFlasterr}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {[@var{msg}, @var{msgid}] =} lasterr ()
@deftypefnx {} {} lasterr (@var{msg})
@deftypefnx {} {} lasterr (@var{msg}, @var{msgid})
Query or set the last error message.

When called without input arguments, return the last error message and
message identifier.

With one argument, set the last error message to @var{msg}.

With two arguments, also set the last message identifier.
@xseealso{@ref{XREFlasterror,,lasterror}, @ref{XREFerror,,error}, @ref{XREFlastwarn,,lastwarn}}
@end deftypefn


The next example counts indexing errors.  The errors are caught using the
field identifier of the structure returned by the function @code{lasterror}.

@example
@group
number_of_errors = 0;
for n = 1:100
  try
    @dots{}
  catch
    id = lasterror.identifier;
    if (strcmp (id, "Octave:invalid-indexing"))
      number_of_errors++;
    endif
  end_try_catch
endfor
@end group
@end example

The functions distributed with Octave can issue one of the following
errors.

@c error_ids scripts/help/error_ids.m
@anchor{XREFerror_ids}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@cindex error ids

@table @code
@item Octave:bad-alloc
Indicates that memory couldn't be allocated.

@item Octave:invalid-context
Indicates the error was generated by an operation that cannot be executed in
the scope from which it was called.  For example, the function
@code{print_usage ()} when called from the Octave prompt raises this error.

@item Octave:invalid-fun-call
Indicates that a function was called in an incorrect way, e.g., wrong number
of input arguments.

@item Octave:invalid-indexing
Indicates that a data-type was indexed incorrectly, e.g., real-value index
for arrays, nonexistent field of a structure.

@item Octave:invalid-input-arg
Indicates that a function was called with invalid input arguments.

@item Octave:parse-error
The interpreter failed to parse (read) specified code.

@item Octave:undefined-function
Indicates a call to a function that is not defined.  The function may exist
but Octave is unable to find it in the search path.

@end table



When an error has been handled it is possible to raise it again.  This
can be useful when an error needs to be detected, but the program should
still abort.  This is possible using the @code{rethrow} function.  The
previous example can now be changed to count the number of errors
related to the @samp{*} operator, but still abort if another kind of
error occurs.

@example
@group
number_of_errors = 0;
for n = 1:100
  try
    @dots{}
  catch
    msg = lasterror.message;
    if (strfind (msg, "operator *"))
      number_of_errors++;
    else
      rethrow (lasterror);
    endif
  end_try_catch
endfor
@end group
@end example

@c rethrow libinterp/corefcn/error.cc
@anchor{XREFrethrow}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {} rethrow (@var{err})
Reissue a previous error as defined by @var{err}.

@var{err} is a structure that must contain at least the @qcode{"message"}
and @qcode{"identifier"} fields.  @var{err} can also contain a field
@qcode{"stack"} that gives information on the assumed location of the
error.  Typically @var{err} is returned from @code{lasterror}.
@xseealso{@ref{XREFlasterror,,lasterror}, @ref{XREFlasterr,,lasterr}, @ref{XREFerror,,error}}
@end deftypefn


@c FIXME: I have no idea what the rest of the functions are used for...

@c errno libinterp/corefcn/utils.cc
@anchor{XREFerrno}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {@var{err} =} errno ()
@deftypefnx {} {@var{err} =} errno (@var{val})
@deftypefnx {} {@var{err} =} errno (@var{name})
Query or set the system-dependent variable errno.

When called with no inputs, return the current value of errno.

When called with a numeric input @var{val}, set the current value of errno
to the specified value.  The previous value of errno is returned as @var{err}.

When called with a character string @var{name}, return the numeric value of
errno which corresponds to the specified error code.  If @var{name} is not
a recognized error code then -1 is returned.

@xseealso{@ref{XREFerrno_list,,errno_list}}
@end deftypefn


@c errno_list libinterp/corefcn/utils.cc
@anchor{XREFerrno_list}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{S} =} errno_list ()
Return a structure containing the system-dependent errno values.
@xseealso{@ref{XREFerrno,,errno}}
@end deftypefn


@node Recovering From Errors
@subsection Recovering From Errors

Octave provides several ways of recovering from errors.  There are
@code{try}/@code{catch} blocks,
@code{unwind_protect}/@code{unwind_protect_cleanup} blocks,
and finally the @code{onCleanup} command.

The @code{onCleanup} command associates an ordinary Octave variable (the
trigger) with an arbitrary function (the action).  Whenever the Octave variable
ceases to exist---whether due to a function return, an error, or simply because
the variable has been removed with @code{clear}---then the assigned function
is executed.

The function can do anything necessary for cleanup such as closing open file
handles, printing an error message, or restoring global variables to their
initial values.  The last example is a very convenient idiom for Octave code.
For example:

@example
@group
function rand42
  old_state = rand ("state");
  restore_state = onCleanup (@@() rand ("state", old_state));
  rand ("state", 42);
  @dots{}
endfunction  # rand generator state restored by onCleanup
@end group
@end example

@c onCleanup libinterp/octave-value/ov-oncleanup.cc
@anchor{XREFonCleanup}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn {} {@var{obj} =} onCleanup (@var{function})
Create a special object that executes a given @var{function} upon destruction.

If the object is copied to multiple variables (or cell or struct array
elements) or returned from a function, then @var{function} will be executed
only after the last copy of the object is cleared.

The input @var{function} is a handle to a function.  The handle may point to an
anonymous function in order to directly place commands in the @code{onCleanup}
call.

Programming Note: If multiple local @code{onCleanup} variables are created, the
order in which they are called is unspecified.  For similar functionality
@xref{The unwind_protect Statement}.

Example

@example
@group
octave:1> trigger = onCleanup (@@() disp ('onCleanup was executed'));
octave:2> clear trigger
onCleanup was executed
octave:3
@end group
@end example

@end deftypefn


@node Handling Warnings
@section Handling Warnings

Like an error, a warning is issued when something unexpected happens.
Unlike an error, a warning doesn't abort the currently running program.
A simple example of a warning is when a number is divided by zero.  In
this case Octave will issue a warning and assign the value @code{Inf}
to the result.

@example
@group
a = 1/0
     @print{} warning: division by zero
     @result{} a = Inf
@end group
@end example

@menu
* Issuing Warnings::
* Enabling and Disabling Warnings::
@end menu

@node Issuing Warnings
@subsection Issuing Warnings

It is possible to issue warnings from any code using the @code{warning}
function.  In its most simple form, the @code{warning} function takes a
string describing the warning as its input argument.  As an example,
the following code controls if the variable @samp{a} is non-negative,
and if not issues a warning and sets @samp{a} to zero.

@example
@group
a = -1;
if (a < 0)
  warning ("'a' must be non-negative.  Setting 'a' to zero.");
  a = 0;
endif
     @print{} 'a' must be non-negative.  Setting 'a' to zero.
@end group
@end example

Since warnings aren't fatal to a running program, it is not possible
to catch a warning using the @code{try} statement or something similar.
It is however possible to access the last warning as a string using the
@code{lastwarn} function.

It is also possible to assign an identification string to a warning.
If a warning has such an ID the user can enable and disable this warning
as will be described in the next section.  To assign an ID to a warning,
simply call @code{warning} with two string arguments, where the first
is the identification string, and the second is the actual warning.  Note
that warning IDs are in the format @qcode{"NAMESPACE:WARNING-NAME"}.  The
namespace @qcode{"Octave"} is used for Octave's own warnings.  Any other string
is available as a namespace for user's own warnings.

@c warning libinterp/corefcn/error.cc
@anchor{XREFwarning}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {} warning (@var{template}, @dots{})
@deftypefnx {} {} warning (@var{id}, @var{template}, @dots{})
@deftypefnx {} {} warning ("on", @var{id})
@deftypefnx {} {} warning ("off", @var{id})
@deftypefnx {} {} warning ("error", @var{id})
@deftypefnx {} {} warning ("query", @var{id})
@deftypefnx {} {} warning (@var{state}, @var{id}, "local")
@deftypefnx {} {} warning (@var{warning_struct})
@deftypefnx {} {@var{warning_struct} =} warning (@dots{})
@deftypefnx {} {} warning (@var{state}, @var{mode})

Display a warning message or control the behavior of Octave's warning system.

The first call form uses a template @var{template} and optional additional
arguments to display a message on the @code{stderr} stream.  The message is
formatted using the same rules as the @code{printf} family of functions
(@pxref{Formatted Output}) and prefixed by the character string
@w{@samp{warning: }}.  You should use this function when you want to notify the
user of an unusual condition, but only when it makes sense for your program to
go on.  For example:

@example
@group
warning ("foo: maybe something wrong here");
@end group
@end example

If the warning message does not end with a newline character, Octave will
print a traceback of all the function calls leading to the warning.  If the
warning message does end in a newline character, Octave will suppress the
traceback messages as it returns control to the top level.  For more details
and examples, @pxref{XREFerror,,@code{error}}.

The optional warning identifier @var{id} allows users to enable or disable
warnings tagged by this identifier.  A message identifier is a string of the
form @qcode{"NAMESPACE:WARNING-NAME"}.  Octave's own warnings use the
@qcode{"Octave"} namespace (@pxref{XREFwarning_ids,,@code{warning_ids}}).  For
example:

@example
@group
warning ("MyNameSpace:check-something",
         "foo: maybe something wrong here");
@end group
@end example

The second call form is meant to change and/or query the state of warnings.
The first input argument must be a string @var{state} (@qcode{"on"},
@qcode{"off"}, @qcode{"error"}, or @qcode{"query"}) followed by an optional
warning identifier @var{id} or @qcode{"all"} (default).

The optional output argument @var{warning_struct} is a structure or structure
array with fields @qcode{"state"} and @qcode{"identifier"}.  The @var{state}
argument may have the following values:

@table @asis
@item @qcode{"on"}|@qcode{"off"}:
Enable or disable the display of warnings identified by @var{id} and optionally
return their previous state @var{stout}.

@item @qcode{"error"}:
Turn warnings identified by @var{id} into errors and optionally return their
previous state @var{stout}.

@item @qcode{"query"}:
Return the current state of warnings identified by @var{id}.
@end table

A structure or structure array @var{warning_struct}, with fields
@qcode{"state"} and @qcode{"identifier"}, may be given as an input to achieve
equivalent results.  The following example shows how to temporarily disable a
warning and then restore its original state:

@example
@group
loglog (-1:10);
## Disable the previous warning and save its original state
[~, id] = lastwarn ();
warnstate = warning ("off", id);
loglog (-1:10);
## Restore its original state
warning (warnstate);
@end group
@end example

If a final argument @qcode{"local"} is provided then the warning state will be
set temporarily until the end of the current function.  Changes to warning
states that are set locally affect the current function and all functions
called from the current scope.  The previous warning state is restored on
return from the current function.  The @qcode{"local"} option is ignored if
used in the top-level workspace.

With no input argument @code{warning ()} is equivalent to
@code{warning ("query", "all")} except that in the absence of an output
argument, the state of warnings is displayed on @code{stderr}.

The level of verbosity of the warning system may also be controlled by two
modes @var{mode}:

@table @asis
@item @qcode{"backtrace"}:
enable/disable the display of the stack trace after the warning message

@item @qcode{"verbose"}:
enable/disable the display of additional information after the warning message
@end table

In this case the @var{state} argument may only be @qcode{"on"} or
@qcode{"off"}.

Implementation Note: For compatibility with @sc{matlab}, escape sequences in
@var{template} (e.g., @qcode{"@backslashchar{}n"} => newline) are processed
regardless of whether @var{template} has been defined with single quotes, as
long as there are two or more input arguments.  To disable escape sequence
expansion use a second backslash before the sequence (e.g.,
@qcode{"@backslashchar{}@backslashchar{}n"}) or use the
@code{regexptranslate} function.
@xseealso{@ref{XREFwarning_ids,,warning_ids}, @ref{XREFlastwarn,,lastwarn}, @ref{XREFerror,,error}}
@end deftypefn


@c lastwarn libinterp/corefcn/error.cc
@anchor{XREFlastwarn}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@deftypefn  {} {[@var{msg}, @var{msgid}] =} lastwarn ()
@deftypefnx {} {} lastwarn (@var{msg})
@deftypefnx {} {} lastwarn (@var{msg}, @var{msgid})
Query or set the last warning message.

When called without input arguments, return the last warning message and
message identifier.

With one argument, set the last warning message to @var{msg}.

With two arguments, also set the last message identifier to @var{msgid}.
@xseealso{@ref{XREFwarning,,warning}, @ref{XREFlasterror,,lasterror}, @ref{XREFlasterr,,lasterr}}
@end deftypefn


The functions distributed with Octave can issue one of the following
warnings.

@c warning_ids scripts/help/warning_ids.m
@anchor{XREFwarning_ids}
@html
<span style="display:block; margin-top:-4.5ex;">&nbsp;</span>
@end html


@cindex warning ids

@table @code
@item Octave:abbreviated-property-match
If the @code{Octave:abbreviated-property-match} warning is enabled, a
warning is printed if a non-exact or ambiguous match is being used for a
operation specifying an object property.  For example, for a graphics
object, @var{fig}, with the property @qcode{'displayname'},
@code{get (@var{fig}, 'dis')} elicits a warning if the
@code{Octave:abbreviated-property-match} warning is enabled.
By default, the @code{Octave:abbreviated-property-match} warning is enabled.

@item Octave:addpath-pkg
If the @code{Octave:addpath-pkg} warning is enabled,
Octave will warn when a package directory (i.e., +package_name) is added
to the @code{path}.  Typically, only the parent directory which contains the
package directory should be added to the load path.
By default, the @code{Octave:addpath-pkg} warning is enabled.

@item Octave:array-as-logical
If the @code{Octave:array-as-logical} warning is enabled,
Octave will warn when an array of size greater than 1x1 is used
as a truth value in an if, while, or until statement.
By default, the @code{Octave:array-as-logical} warning is disabled.

@item Octave:array-to-scalar
If the @code{Octave:array-to-scalar} warning is enabled, Octave will
warn when an implicit conversion from an array to a scalar value is
attempted.
By default, the @code{Octave:array-to-scalar} warning is disabled.

@item Octave:array-to-vector
If the @code{Octave:array-to-vector} warning is enabled, Octave will
warn when an implicit conversion from an array to a vector value is
attempted.
By default, the @code{Octave:array-to-vector} warning is disabled.

@item Octave:assign-as-truth-value
If the @code{Octave:assign-as-truth-value} warning is
enabled, a warning is issued for statements like

@example
@group
if (s = t)
  @dots{}
@end group
@end example

@noindent
since such statements are not common, and it is likely that the intent
was to write

@example
@group
if (s == t)
  @dots{}
@end group
@end example

@noindent
instead.

There are times when it is useful to write code that contains
assignments within the condition of a @code{while} or @code{if}
statement.  For example, statements like

@example
@group
while (c = getc ())
  @dots{}
@end group
@end example

@noindent
are common in C programming.

It is possible to avoid all warnings about such statements by
disabling the @code{Octave:assign-as-truth-value} warning,
but that may also let real errors like

@example
@group
if (x = 1)  # intended to test (x == 1)!
  @dots{}
@end group
@end example

@noindent
slip by.

In such cases, it is possible suppress errors for specific statements by
writing them with an extra set of parentheses.  For example, writing the
previous example as

@example
@group
while ((c = getc ()))
  @dots{}
@end group
@end example

@noindent
will prevent the warning from being printed for this statement, while
allowing Octave to warn about other assignments used in conditional
contexts.

By default, the @code{Octave:assign-as-truth-value} warning is enabled.

@item Octave:autoload-relative-file-name
If the @code{Octave:autoload-relative-file-name} is enabled,
Octave will warn when parsing autoload() function calls with relative
paths to function files.  This usually happens when using autoload()
calls in PKG_ADD files, when the PKG_ADD file is not in the same
directory as the .oct file referred to by the autoload() command.
By default, the @code{Octave:autoload-relative-file-name} warning is
enabled.

@item Octave:charmat-truncated
If the @code{Octave:charmat-truncated} warning is enabled, a warning is
printed when a character matrix with multiple rows is converted to a string.
In this case, the Octave interpreter keeps only the first row and discards
the others.
By default, the @code{Octave:charmat-truncated} warning is enabled.

@item Octave:classdef-to-struct
If the @code{Octave:classdef-to-struct} warning is enabled, a warning
is issued when a classdef object is forcibly converted into a struct with
@code{struct (@var{CLASSDEF_OBJ})}.  Conversion removes the access
restrictions from the object and makes private and protected properties
visible.
By default, the @code{Octave:classdef-to-struct} warning is enabled.

@item Octave:colon-complex-argument
If the @code{Octave:colon-complex-argument} warning is enabled, a warning
is issued when one of the three arguments to the colon operator (base,
increment, limit) is a complex value.  For example, @code{1:3*i} will
cause a warning to be emitted.
By default, the @code{Octave:colon-complex-argument} warning is enabled.

@item Octave:colon-nonscalar-argument
If the @code{Octave:colon-nonscalar-argument} warning is enabled, a warning
is issued when one of the three arguments to the colon operator (base,
increment, limit) is not a scalar.  For example, @code{1:[3, 5]} will
cause a warning to be emitted.
By default, the @code{Octave:colon-nonscalar-argument} warning is enabled.

@item Octave:data-file-in-path
If the @code{Octave:data-file-in-path} warning is enabled, a warning is
issued when Octave does not find the target of a file operation such as
@code{load} or @code{fopen} directly, but is able to locate the file in
Octave's search @code{path} for files.  The warning could indicate that a
different file target than the programmer intended is being used.
By default, the @code{Octave:data-file-in-path} warning is enabled.

@item Octave:datevec:date-format-spec
If the @code{Octave:datevec:date-format-spec} warning is enabled, a warning
is printed if the date format specification contains questionable date or
time specifiers.  Typical bad patterns are using uppercase date specifiers
or lowercase time specifiers.
By default, the @code{Octave:datevec:date-format-spec} warning is enabled.

@item Octave:deprecated-function
If the @code{Octave:deprecated-function} warning is enabled, a
warning is issued when Octave encounters a function that is obsolete and
scheduled for removal from Octave.
By default, the @code{Octave:deprecated-function} warning is enabled.

@item Octave:deprecated-keyword
If the @code{Octave:deprecated-keyword} warning is enabled, a
warning is issued when Octave encounters a keyword that is obsolete and
scheduled for removal from Octave.
By default, the @code{Octave:deprecated-keyword} warning is enabled.

@item Octave:deprecated-option
If the @code{Octave:deprecated-option} warning is enabled, a
warning is issued when an obsolete option or input to a function is used.
By default, the @code{Octave:deprecated-option} warning is enabled.

@item Octave:deprecated-property
If the @code{Octave:deprecated-property} warning is enabled, a
warning is issued when Octave encounters a graphics property that
is obsolete and scheduled for removal from Octave.
By default, the @code{Octave:deprecated-property} warning is enabled.

@item Octave:eigs:UnconvergedEigenvalues
If the @code{Octave:eigs:UnconvergedEigenvalues} warning is enabled then
the eigs function will issue a warning if the number of calculated
eigenvalues is less than the number of requested eigenvalues.
By default, the @code{Octave:eigs:UnconvergedEigenvalues} warning is
enabled.

@item Octave:empty-index
If the @code{Octave:empty-index} warning is enabled then Octave will emit a
warning whenever indexing operators are used without an index, for example
@code{@var{x}()}.
By default, the @code{Octave:empty-index} warning is enabled.

@item Octave:erase:chararray
If the @code{Octave:erase:chararray} warning is enabled then the erase
function will issue a warning if the input pattern is a character array
rather than a string or cell array of strings.
By default, the @code{Octave:erase:chararray} warning is enabled.

@item Octave:function-name-clash
If the @code{Octave:function-name-clash} warning is enabled, a
warning is issued when Octave finds that the name of a function
defined in a function file differs from the name of the file.  (If
the names disagree, the name declared inside the file is ignored.)
By default, the @code{Octave:function-name-clash} warning is enabled.

@item Octave:future-time-stamp
If the @code{Octave:future-time-stamp} warning is enabled, Octave
will print a warning if it finds a function file with a time stamp
that is in the future.
By default, the @code{Octave:future-time-stamp} warning is enabled.

@item Octave:glyph-render
If the @code{Octave:glyph-render} warning is enabled, Octave will
print a warning if the glyph for a character couldn't be rendered with
the current font.
By default, the @code{Octave:glyph-render} warning is enabled.

@item Octave:imag-to-real
If the @code{Octave:imag-to-real} warning is enabled, a warning is
printed for implicit conversions of complex numbers to real numbers.
By default, the @code{Octave:imag-to-real} warning is disabled.

@item Octave:infinite-loop
If the @code{Octave:infinite-loop} warning is enabled, a warning is
printed when an infinite loop is detected such as @code{for i = 1:Inf} or
@code{while (1)}.
By default, the @code{Octave:infinite-loop} warning is enabled.

@item Octave:language-extension
Print warnings when using features that are unique to the Octave
language and that may still be missing in @sc{matlab}.
By default, the @code{Octave:language-extension} warning is disabled.
The @option{--traditional} or @option{--braindead} startup options for
Octave may also be of use, @pxref{Command Line Options}.

@item Octave:legacy-function
If the @code{Octave:legacy-function} warning is enabled, a
warning is issued when Octave encounters a function that @sc{matlab} has
suggested should be avoided.  The function may become obsolete at some
point in the future and removed, in which case the warning will change to
@code{Octave:deprecated-function}, and the function will continue to exist
for two further versions of Octave before being removed.
By default, the @code{Octave:legacy-function} warning is enabled.

@item Octave:logical-conversion
If the @code{Octave:logical-conversion} warning is enabled, a warning is
printed if an implicit conversion of an array from numerical to boolean
occurs and any of the elements in the array are not equal to zero or one.
By default, the @code{Octave:logical-conversion} warning is enabled.

@item Octave:lu:sparse_input
If the @code{Octave:lu:sparse_input} warning is enabled, Octave
will warn when the lu function is called with a sparse input and less than
four output arguments.  In this case, sparsity-preserving column
permutations are not performed and the result may be inaccurate.
By default, the @code{Octave:lu:sparse_input} warning is enabled.

@item Octave:missing-glyph
If the @code{Octave:glyph-render} warning is enabled, Octave will
print a warning if the current font doesn't provide a glyph for a
used character.
By default, the @code{Octave:missing-glyph} warning is enabled.

@item Octave:missing-semicolon
If the @code{Octave:missing-semicolon} warning is enabled, Octave
will warn when statements in function definitions don't end in
semicolons.
By default the @code{Octave:missing-semicolon} warning is disabled.

@item Octave:mixed-string-concat
If the @code{Octave:mixed-string-concat} warning is enabled, print a
warning when concatenating a mixture of single and double quoted strings.
By default, the @code{Octave:mixed-string-concat} warning is disabled.

@item  Octave:nearly-singular-matrix
@itemx Octave:singular-matrix
These warnings are emitted if a (nearly) singular matrix is inverted.
By default, the @code{Octave:nearly-singular-matrix} and
@code{Octave:singular-matrix} warnings are enabled.

@item Octave:neg-dim-as-zero
If the @code{Octave:neg-dim-as-zero} warning is enabled, print a warning
for expressions like

@example
eye (-1)
@end example

@noindent
By default, the @code{Octave:neg-dim-as-zero} warning is disabled.

@item Octave:noninteger-range-as-index
If the @code{Octave:noninteger-range-as-index} warning is enabled, a warning
is printed if an array is indexed with a range that contains non-integer
values.  For example,

@example
@group
a = [1 2 3 4 5];
b = 2.2:4.2
@result{} 1.2  2.2  3.2
a(b)
@result{} 2 3 4
@end group
@end example

@noindent
elicits a warning if the @code{Octave:noninteger-range-as-index} warning is
enabled.
By default, the @code{Octave:noninteger-range-as-index} warning is enabled.

@item Octave:num-to-str
If the @code{Octave:num-to-str} warning is enabled, a warning is
printed for implicit conversions of numbers to their UTF-8 encoded character
equivalents when strings are constructed using a mixture of strings and
numbers in matrix notation.  For example,

@example
@group
[ "f", 111, 111 ]
@result{} "foo"
@end group
@end example

@noindent
elicits a warning if the @code{Octave:num-to-str} warning is
enabled.  By default, the @code{Octave:num-to-str} warning is enabled.

@item Octave:possible-matlab-short-circuit-operator
If the @code{Octave:possible-matlab-short-circuit-operator} warning
is enabled, Octave will warn about using the not short circuiting
operators @code{&} and @code{|} inside @code{if} or @code{while}
conditions.  They normally never short circuit, but they do short
circuit when used in a condition.
By default, the @code{Octave:possible-matlab-short-circuit-operator} warning
is enabled.

@item Octave:pow2:imaginary-ignored
If the @code{Octave:pow2:imaginary-ignored} warning is enabled, a warning is
printed if either input to @code{pow2} is complex.
By default, the @code{Octave:pow2:imaginary-ignored} warning is enabled.

@item Octave:recursive-path-search
If the @code{Octave:recursive-path-search} warning is enabled, Octave
will issue a warning if @code{addpath} is used with double trailing
slashes.
By default, the @code{Octave:recursive-path-search} warning is enabled.

@item Octave:remove-init-dir
The @code{path} function changes the search path that Octave uses
to find functions.  It is possible to set the path to a value which
excludes Octave's own built-in functions.  If the
@code{Octave:remove-init-dir} warning is enabled then Octave will warn
when the @code{path} function has been used in a way that may render
Octave unworkable.
By default, the @code{Octave:remove-init-dir} warning is enabled.

@item Octave:reload-forces-clear
If several functions have been loaded from the same file, Octave must
clear all the functions before any one of them can be reloaded.  If
the @code{Octave:reload-forces-clear} warning is enabled, Octave will
warn you when this happens, and print a list of the additional
functions that it is forced to clear.
By default, the @code{Octave:reload-forces-clear} warning is enabled.

@item Octave:separator-insert
Print warning if commas or semicolons might be inserted
automatically in literal matrices.
By default, the @code{Octave:separator-insert} warning is disabled.

@item Octave:shadowed-function
If the @code{Octave:shadowed-function} warning is enabled, Octave will
warn if a path is added to the search path that contains functions
that shadow core functions.
By default, the @code{Octave:shadowed-function} warning is enabled.

@item Octave:single-quote-string
Print warning if a single quote character is used to introduce a
string constant.
By default, the @code{Octave:single-quote-string} warning is disabled.

@item Octave:sparse:double-conversion
If the @code{Octave:sparse:double-conversion} warning is enabled, a warning
is printed when an implicit conversion from a full, single array occurs
during the creation of a sparse array.
By default, the @code{Octave:sparse:double-conversion} warning is enabled.

@item Octave:sqrtm:SingularMatrix
If the @code{Octave:sqrtm:SingularMatrix} warning is enabled, a warning is
printed if the matrix square root function @code{sqrtm} is called with an
input matrix that is singular.
By default, the @code{Octave:sqrtm:SingularMatrix} warning is enabled.

@item Octave:str-to-num
If the @code{Octave:str-to-num} warning is enabled, a warning is printed
for implicit conversions of strings to their numeric UTF-8 encoded byte
sequences.  For example,

@example
@group
"abc" + 0
@result{} 97 98 99
@end group
@end example

@noindent
elicits a warning if the @code{Octave:str-to-num} warning is enabled.
By default, the @code{Octave:str-to-num} warning is disabled.

@item Octave:LaTeX:internal-error
If the @code{Octave:LaTeX:internal-error} warning is enabled, a warning is
printed whenever the @LaTeX{} renderer for text in plots encounters an
issue.
By default, the @code{Octave:LaTeX:internal-error} warning is enabled.

@item Octave:unimplemented-matlab-functionality
If the @code{Octave:unimplemented-matlab-functionality} warning is enabled,
a warning is printed when a @sc{matlab} code construct is used which the
Octave interpreter parses as valid, but for which Octave does not yet
implement the functionality.
By default, the @code{Octave:unimplemented-matlab-functionality} warning is
enabled.

@item Octave:variable-switch-label
If the @code{Octave:variable-switch-label} warning is enabled, Octave
will print a warning if a switch label is not a constant or constant
expression.
By default, the @code{Octave:variable-switch-label} warning is disabled.
@end table



@node Enabling and Disabling Warnings
@subsection Enabling and Disabling Warnings

The @code{warning} function also allows you to control which warnings
are actually printed to the screen.  If the @code{warning} function
is called with a string argument that is either @qcode{"on"} or @qcode{"off"}
all warnings will be enabled or disabled.

It is also possible to enable and disable individual warnings through
their string identifications.  The following code will issue a warning

@example
@group
warning ("example:non-negative-variable",
         "'a' must be non-negative.  Setting 'a' to zero.");
@end group
@end example

@noindent
while the following won't issue a warning

@example
@group
warning ("off", "example:non-negative-variable");
warning ("example:non-negative-variable",
         "'a' must be non-negative.  Setting 'a' to zero.");
@end group
@end example