title | description | author | ms.author | ms.date | ms.service | ms.subservice | ms.topic | helpviewer_keywords | |||
---|---|---|---|---|---|---|---|---|---|---|---|
Visual FoxPro ODBC Driver Native Error Messages |
Visual FoxPro ODBC Driver Native Error Messages |
David-Engel |
v-davidengel |
01/19/2017 |
sql |
connectivity |
conceptual |
|
Visual FoxPro ODBC Driver Native Error Messages
The following tables list error messages native to the Visual FoxPro ODBC Driver.
001
Error code | Error message |
---|---|
1 | Feature is not available. |
2 | Input/output operation failure. |
3 | Free handle is not found. |
5 | Use of unallocated handle. |
99 | Procedure canceled. |
100
Error code | Error message |
---|---|
100 | Too many files open. |
101 | Cannot open file. |
102 | Cannot create file. |
105 | Error writing to file. |
107 | Invalid key length. |
109 | Record is out of range. |
110 | Record is not in index. |
111 | Invalid file descriptor. |
113 | File is not open. |
114 | Not enough disk space for value. |
115 | Invalid operation for the cursor. |
118 | Index file does not match table. |
119 | No table is open. |
120 | File does not exist. |
121 | File already exists. |
122 | Table has no index order set. |
123 | Not a table. |
125 | Index expression exceeds maximum length. |
127 | You must use a logical expression with a FOR or WHILE clause. |
128 | Not a numeric expression. |
129 | Variable is not found. |
132 | File is in use. |
133 | Index does not match the table. Delete the index file and re-create the index. |
135 | End of file encountered. |
136 | Beginning of file encountered. |
137 | Alias is not found. |
139 | You must use a logical expression with FILTER. |
142 | Cyclic relation. |
143 | No fields were found to copy. |
144 | The LOCATE command must be issued before the CONTINUE command. |
145 | Must be a character or numeric key field. |
146 | Cannot write to a read-only file. |
147 | Target table is already engaged in a relation. |
148 | Expression has been re-entered while the filter is executing. |
149 | Not enough memory for buffer. |
150 | Not enough memory for file map. |
155 | Invalid buffdirty call. |
156 | Duplicate field names. |
158 | No fields found to process. |
159 | Numeric overflow. Data was lost. |
162 | Procedure ‘value‘ is not found. |
165 | value is not related to the current work area. |
170 | Variable ‘value‘ is not found. |
171 | Cannot open file value. |
173 | File ‘value‘ does not exist. |
174 | ‘value‘ is not a memory variable. |
175 | ‘value‘ is not a file variable. |
176 | ‘value‘ is not an array. |
177 | Alias ‘value‘ is not found. |
180 | File was not placed in memory using the LOAD command. |
182 | There is not enough memory to complete this operation. |
200
Error code | Error message |
---|---|
200 | Syntax error. |
201 | Too many names used. |
202 | Program is too large. |
203 | Too many memory variables. |
205 | Nesting error. |
206 | Recursive macro definition. |
209 | Line is too long. |
210 | Allowed DO nesting level exceeded. |
211 | An IF | ELSE | ENDIF statement is missing. |
212 | Structure nesting is too deep. |
213 | There is a missing keyword in the FOR…ENDFOR or DO CASE…ENDCASE command structure. |
219 | Command contains unrecognized phrase/keyword. |
221 | Command is missing required clause. |
222 | Unrecognized command verb. |
224 | Invalid subscript reference. |
227 | Missing expression. |
228 | Table number is invalid. |
229 | Too few arguments. |
230 | Too many arguments. |
233 | Statement is not allowed in interactive mode. |
234 | Subscript is outside defined range. |
236 | Suspend program before using RESUME. |
238 | No PARAMETER statement is found. |
239 | Must specify additional parameters. |
240 | Not a character expression. |
250 | Too many PROCEDURE commands are in effect. |
252 | Compiled code for this line is too long. |
257 | Key string is too long. |
291 | Expression used with ASIN() is out of range. |
292 | Cannot use 0 or negative as the argument for LOG10(). |
293 | Expression used with ACOS() is out of range. |
294 | FOXUSER.DBF file is invalid. |
295 | Invalid path or file name. |
296 | Error reading the resource. |
297 | Command is allowed only in interactive mode. |
300
Error code | Error message |
---|---|
301 | Operator/operand type mismatch. |
302 | Data type mismatch. |
305 | Expression evaluated to an illegal value. |
307 | Cannot divide by 0. |
308 | Insufficient stack space. |
337 | Cannot nest the PRINTJOB command. |
400
Error code | Error message |
---|---|
406 | Printer is not ready. |
407 | Invalid argument used with the SET function. |
410 | Unable to create temporary work files. |
423 | Error creating the OLE object. |
424 | Error copying the OLE object to the Clipboard. |
462 | value internal consistency error. |
465 | SQL pass-through internal consistency error. |
466 | Connection handle is invalid. |
467 | Property is invalid for local cursors. |
468 | Property is invalid for table cursors. |
469 | Property value is out of bounds. |
470 | Incorrect property name. |
471 | Incorrect column format. |
473 | Environment-level property is invalid. |
474 | Invalid call issued while executing a SQLEXEC() sequence. |
479 | Invalid update column name value. |
489 | General fields cannot be used in the WHERE condition of an update statement. Change the WhereType property of the view. |
491 | No update tables are specified. Use the Tables property of the cursor. |
492 | No key columns are specified for the update table value. Use the KeyFieldList property of the cursor. |
493 | SQL parameter is missing. |
494 | View definition has been changed. |
495 | Warning: The key defined by the KeyField property for table value is not unique. |
498 | SQL SELECT statement is invalid. |
499 | SQL parameter value is invalid. |
500
Error code | Error message |
---|---|
502 | Cannot write to the record because it is in use. |
503 | File cannot be locked. |
508 | Error initializing OLE. |
520 | No database is open or set as the current database. |
522 | Connectivity internal consistency error. |
523 | Execution was canceled by the user. |
525 | Function is not supported on remote tables. |
526 | Connectivity error: value. |
527 | Cannot load ODBC library, ODBC32.DLL. |
528 | ODBC entry point missing, value. |
530 | Fetching canceled; remote table is closed. |
532 | Type conversion is not supported. |
533 | This property is read-only. |
536 | Function is not supported on native tables. |
538 | A stored procedure is executing. |
540 | Session number is invalid. |
541 | Connection value is busy. |
542 | Base table fields have been changed and no longer match view fields. View field properties cannot be set. |
543 | Type conversion required by the DataType property for field ‘value‘ is invalid. |
544 | DataType property for field ‘value‘ is invalid. |
545 | Table buffer for alias value contains uncommitted changes. |
546 | Cannot close table during execution of table-bound expression. |
547 | Cannot insert an empty row from a view into its base table(s). |
548 | Table value has one or more non-structural indexes open. Please close them and retry the Begin Transaction. |
549 | Data session #value cannot be released with open transaction(s). |
550 | .DBC internal consistency error. |
557 | The database must be opened exclusively. |
559 | Property is not found. |
560 | Property value is invalid. |
561 | Database is invalid. Please validate. |
562 | Cannot find object value in the database. |
563 | Cannot find view value in the current database. |
566 | Cannot issue the PACK command on a database while its tables are in use. |
567 | Primary key property is invalid; please validate database. |
570 | Database is read-only. |
571 | The name value is already used for another |
575 | Object name is invalid. |
577 | Table value is referenced in a relation. |
578 | Invalid database table name. |
579 | Command cannot be issued on a table with cursors in table buffering mode. |
580 | Feature is not supported for non-.DBC tables. |
581 | Field value does not accept null value. |
583 | Record validation rule is violated. |
585 | Update conflict. Use TABLEUPDATE() with the lForce parameter to commit the update or TABLEREVERT() to roll back the update. |
586 | Function requires row or table buffering mode. |
587 | Illegal nested OLDVAL() or CURVAL(). |
589 | Table or row buffering requires that SET MULTILOCKS is set to ON. |
590 | BEGIN TRANSACTION command failed. Nesting level is too deep. |
591 | END TRANSACTION command cannot be issued without a corresponding BEGIN TRANSACTION command. |
592 | ROLLBACK command cannot be issued without a corresponding BEGIN TRANSACTION command. |
593 | Command cannot be issued within a transaction. |
594 | Illegal to attempt a file lock in a transaction after taking prior record locks. |
596 | Table buffering is not enabled. |
597 | Views require either DB_BUFOPTROW or DB_BUFOPTTABLE. |
598 | Rule and trigger code must balance transaction usage. |
599 | Data session #value was forced to ROLLBACK all transactions to avoid deadlock. |
600
Error code | Error message |
---|---|
601 | Alias name is already in use. |
602 | Operation is invalid for a Memo, General, or Picture field. |
612 | No such menu or menu item is defined. |
618 | Menu has not been defined with DEFINE MENU. |
624 | Menu title has not been defined with DEFINE PAD. |
625 | Menu has not been defined with DEFINE POPUP. |
631 | Array dimensions are invalid. |
637 | File must be opened exclusively to convert the Memo file. |
638 | Field must be a Memo field. |
649 | No previous PRINTJOB command to correspond to this command. |
651 | CANCEL or SUSPEND is not allowed. |
659 | The table has memo fields that cannot be converted while open read-only. |
683 | Index tag is not found. |
700
Error code | Error message |
---|---|
700 | Record is in use by another user. |
701 | File must be opened exclusively. |
702 | File is in use by another user. |
703 | Record is not locked. |
705 | File access is denied. |
706 | Cannot sort .IDX files in descending order. |
707 | Structural .CDX file is not found. |
708 | File is open in another work area. |
712 | Field name is a duplicate or invalid. |
714 | Window ‘value‘ has not been defined. |
718 | File is read-only. |
722 | Preprocessor expression is invalid. |
734 | Property value is not found. |
737 | value is a method, event, or object. |
738 | Property value is not a method or event. |
740 | value is a read-only property. |
748 | This file is incompatible with the current version of Visual FoxPro. |
750 | File was created in a later version of Visual FoxPro than the current version. |
763 | Property value already exists. |
773 | Database object type is invalid. |
784 | This object is derived from a base class and does not have a parent class. |
800
Error code | Error message |
---|---|
802 | SQL: Cannot locate table. |
872 | Too many columns. |
879 | No primary key. |
884 | Uniqueness of index value is violated. |
885 | Only structural tags can be defined as candidate. |
886 | Index does not accept NULL. |
887 | Illegal recursion in rule evaluation. |
888 | Tag name is too long. |
900
Error code | Error message |
---|---|
901 | Function argument value, type, or count is invalid. |
902 | Expression evaluator failed. |
903 | String is too long to fit. |
904 | ** or ^ domain error. |
905 | LOG(): Zero or negative used as argument. |
906 | SQRT() argument cannot be negative. |
912 | Operation is invalid for a General field. |
914 | Code page number is invalid. |
915 | Collating sequence ‘value‘ is not found. |
918 | File name is too long. |
922 | Volume does not exist. |
923 | Object value is not found. |
924 | value is not an object. |
925 | Unknown member value. |
928 | Statement is only valid within a class definition. |
929 | value can only be used within a method. |
930 | Cannot redefine value. |
931 | Statement is not in a procedure. |
934 | Statement is only valid within a method. |
935 | The current object does not inherit from class value. |
937 | Procedure file ‘value‘ is not found. |
938 | Object is not contained in a value. |
939 | WITH/ENDWITH mismatch. |
940 | Expression is not valid outside of WITH/ENDWITH. |
941 | Error code is invalid. |
942 | Objects cannot be assigned to arrays. |
943 | Member value does not evaluate to an object. |
945 | The current object has been released. |
947 | Expression is too complex. |
951 | Cannot clear the object in use. |
955 | WIN.INI/registry is corrupted. |
957 | Error accessing printer spooler. |
959 | Invalid coordinates. |
960 | Illegal redefinition of variable value. |
971 | Cannot compile until the current COMPILE command has completed. |
972 | Array value is in use. |
974 | Arrays cannot be assigned to array elements. |
976 | Cannot resolve backlink. |
988 | Currency value is out of range. |
990 | Cancel. |
999 | Function is not implemented. |
Article: Q134636
Product(s): Microsoft FoxPro
Version(s): WINDOWS:3.0
Operating System(s):
Keyword(s): kbvfp300 kbvfp600
Last Modified: 18-JUL-2000
-------------------------------------------------------------------------------
The information in this article applies to:
- Microsoft Visual FoxPro for Windows, version 3.0
-------------------------------------------------------------------------------
SUMMARY
=======
The following list shows those error messages with the corresponding error
numbers that have been modified (the wording has changed) in Microsoft Visual
FoxPro. This list does not include error numbers new to Microsoft Visual FoxPro.
MORE INFORMATION
================
1 File does not exist.
11 Function argument value, type, or count is invalid.
12 Variable <variable> is not found.
13 Alias is not found.
15 Not a table.
17 Table number is invalid.
18 Line is too long.
21 Length of memory variable strings exceeds amount of memory.
23 Index expression exceeds maximum length.
24 Alias name is already in use.
26 Table has no index order set.
30 Row or column position is off the screen.
34 Operation is invalid for a Memo, General, or Picture field.
36 Command contains unrecognized phrase/keyword.
37 You must use a logical expression with FILTER.
39 Numeric overflow. Data was lost.
41 Memo file <name> is missing or is invalid.
42 The LOCATE command must be issued before the CONTINUE command.
43 There is not enough memory to complete this operation.
46 Expression evaluated to an illegal value.
47 No fields found to process.
50 Report file is invalid.
52 No table is open.
54 Label file is invalid.
55 Memory variable file is invalid.
58 LOG(): Zero or negative used as argument.
61 SQRT() argument cannot be negative.
62 Cannot access characters beyond string.
67 Expression evaluator failed.
91 File was not placed in memory using the LOAD command.
94 Must specify additional parameters.
95 Statement is not allowed in interactive mode.
101 Cannot open file.
103 Allowed DO nesting level exceeded.
108 File is in use by another user.
109 Record is in use by another user.
110 File must be opened exclusively.
111 Cannot update the cursor.
114 Index does not match the table. Delete the index file
and re-create the index.
115 .DIF file header is invalid.
116 .DIF vector is invalid - .DBF field mismatch.
117 .DIF type indicator is invalid.
119 .SYLK file header is invalid.
120 .SYLK file dimension bounds are invalid.
121 .SYLK file format is invalid.
124 Printer redirection is invalid.
125 Printer is not ready.
127 View file is invalid.
164 Menu title has not been defined with DEFINE PAD.
165 Menu has not been defined with DEFINE POPUP.
166 No menu items have been defined for this menu.
167 Menu item position must be a positive number.
168 Menu has not been defined with DEFINE MENU.
169 Cannot define menu item.
170 Cannot release menu item.
174 Cannot redefine a menu that is in use.
175 Cannot redefine a popup that is in use.
176 Cannot clear a menu that is in use.
177 Cannot clear a popup that is in use.
178 Menu has not been activated with ACTIVATE MENU.
179 Menu has not been activated with ACTIVATE POPUP.
181 Menu specified in ACTIVATE MENU is already in use.
182 Menu specified in ACTIVATE POPUP is already in use.
202 Invalid path or file name.
214 Window has not been defined with DEFINE WINDOW.
215 Window has not been activated with ACTIVATE WINDOW.
216 Display mode is not available.
221 Left margin including indent must be less than the right margin.
225 <name> is not a memory variable.
226 <name> is not a file variable.
227 Box dimensions are invalid.
230 Array dimensions are invalid.
231 Invalid argument used with the SET function.
232 <name> is not an array.
279 Menu was not pushed.
287 Menu size is too small.
291 Expression used with ASIN() is out of range.
292 Cannot use 0 or negative as the argument for LOG10().
293 Expression used with ACOS() is out of range.
297 Lotus 1-2-3 version 2.0 file format is invalid.
332 Window specified in DEFINE WINDOW has invalid coordinates.
355 Macro is not defined.
356 Keyboard macro file format is invalid.
392 Maximum record length exceeded in the import file.
1001 Feature is not available.
1002 Input/output operation failure.
1103 Invalid seek offset.
1104 Error reading file.
1105 Error writing to file.
1106 Cannot access file; transaction is in progress.
1108 Picture too big, corrupt, or in wrong format.
1112 Error closing the file.
1113 File is not open.
1115 Invalid operation for the cursor.
1117 Key field length does not match.
1124 Key exceeds allowed size.
1126 Record is too long.
1127 You must use a logical expression with a FOR or WHILE clause.
1130 'field' phrase is not found.
1134 Variable must be in the selected table.
1140 FILTER expression exceeds allowed size.
1141 Unrecognized index file revision. Re-create the index.
1145 Must be a character or numeric key field.
1147 Target table is already engaged in a relation.
1148 Expression has been re-entered while the filter is executing.
1149 Not enough memory for buffer.
1150 Not enough memory for file map.
1151 Not enough memory for filename.
1152 Cannot access the selected table.
1153 Cannot rename the file to different device.
1157 Cannot update the file.
1161 Too many records to browse or edit in the demo version.
1162 Procedure <procedure> is not found.
1163 Browse table is closed.
1164 Browse structure has changed.
1165 <field> is not related to the current work area.
1178 Application file <file> is not closed.
1195 Object file <file> was compiled in a previous version of FoxPro.
1196 <file> is not a Visual FoxPro .EXE file.
1202 Program is too large.
1211 An IF | ELSE | ENDIF statement is missing.
1212 Structure nesting is too deep.
1213 CASE, ENDCASE, or OTHERWISE does not have corresponding
DO CASE statement.
1214 ENDTEXT does not have corresponding TEXT statement.
1220 Command contains invalid character.
1221 Command is missing required clause.
1225 Must be a memory or array variable.
1232 DIMENSION contains variable declaration without required
subscript arguments.
1234 Subscript is outside defined range.
1235 Structure is invalid.
1238 No PARAMETER statement is found.
1241 Improper data type in the group expression.
1242 Syntax error in the field expression.
1243 Internal error: Too many characters in the report.
1245 Invalid expression in label definition file.
1246 Total label width exceeds allowed size.
1249 Too many READ commands are in effect.
1250 Too many PROCEDURE commands are in effect.
1252 Compiled code for this line is too long.
1253 Cannot rename the current directory.
1254 Cannot nest key labels.
1255 Key label <label> is invalid.
1257 Key string is too long.
1294 FOXUSER.DBF file is invalid.
1296 Error reading the resource.
1300 Function name is missing ).
1304 Function name is missing (.
1306 Missing comma (,).
1307 Cannot divide by 0.
1309 <file> is not an object file.
1310 Too many characters are specified in the PICTURE clause.
1337 Cannot nest the PRINTJOB command.
1405 RUN|! command failed.
1410 Unable to create temporary work files.
1411 RUN|! command string is too long.
1412 Cannot locate the COMSPEC environment variable.
1420 OLE object is invalid or corrupted.
1421 Cannot activate the OLE server.
1422 Error saving the OLE object.
1423 Error creating the OLE object.
1424 Error copying the OLE object to Clipboard.
1502 Cannot write to the record because it is in use.
1507 Screen code is too large for available memory.
1600 Not enough memory to open a table with the USE command.
1604 No menu item is defined.
1605 No menu is defined.
1607 Maximum menu items allowed (128) is exceeded.
1608 Maximum menus allowed (25) is exceeded.
1611 Menu items and titles must be type Character.
1612 No such menu or menu item is defined.
1621 No menu titles have been defined for this menu.
1632 Window file format is invalid.
1637 File must be opened exclusively to convert the Memo file.
1642 Color set resource is not found.
1644 Printer driver is not found.
1645 Report contains a nesting error.
1646 Total field type must be Date or Numeric.
1647 Field expression contains an invalid data type.
1649 No previous PRINTJOB command to correspond to this command.
1651 CANCEL or SUSPEND is not allowed.
1652 Invalid use of a Visual FoxPro function as an array.
1657 Column number must be between 0 and the right margin.
1659 The table has memo fields that cannot be converted while
open read-only.
1661 Microsoft Excel file format is invalid.
1662 Lotus 1-2-3 version 1.0 file format is invalid.
1670 Multiplan version 4.0 file format is invalid.
1671 Cannot import from password-protected file.
1673 Symphony version 1.0 file format is invalid.
1674 Symphony version 1.1 file format is invalid.
1678 Lotus 1-2-3 version 3.0 file format is invalid.
1681 PREVIEW clause is not allowed with OFF/NOCONSOLE or TO PRINT/FILE.
1683 Index tag is not found.
1684 Index tag or file name must be specified.
1686 Form file <name> is invalid.
1687 Menu file is invalid.
1688 Paradox file format is invalid.
1689 Cannot build an .APP or .EXE file without a main program.
1690 Table operation is invalid during indexing.
1691 Library file <name> is invalid.
1693 Cannot find the menu-generation program.
1694 Too many extensions are specified.
1695 COLUMN | FORM | ALIAS | NOOVERWRITE | WIDTH are only allowed
with the FROM clause.
1696 NOWAIT/SAVE/NOENVIRONMENT/IN/WINDOW clauses are not allowed
with the FROM clause.
1698 COLUMN | ROW | ALIAS | NOOVERWRITE | SIZE | SCREEN are only
allowed with the FROM clause.
1705 File access is denied.
1706 Cannot sort .IDX files in descending order.
1707 Structural .CDX file is not found.
1710 MULTISELECT or MOVER clause is not supported for PROMPT style menus.
1711 API library revision mismatch. Rebuild library.
1712 Field name is a duplicate or invalid.
1713 Field width or number of decimal places is invalid.
1715 Server <server> is not found.
1716 Queue <queue> is not found.
1718 File is read-only.
1719 Object file <name> is in use and cannot be removed from memory.
1720 Cannot issue the SET FORMAT command while a READ command is
in progress on a format file.
1722 Preprocessor expression is invalid.
1723 Mismatched #IF/#ELSIF/#ELSE/#ENDIF.
1724 Missing #ENDIF.
1725 Constant is already created with #DEFINE.
1726 API library is not found.
1727 A .DBF-style Help file is required.
1800 SQL: Internal error.
1801 SQL: Error correlating fields.
1802 SQL: Cannot locate table.
1803 SQL: HAVING clause is invalid.
1804 SQL: Statement is invalid.
1805 SQL: Too many subqueries.
1806 SQL: Column <field> | <variable> is not found.
1807 SQL: GROUP BY clause is invalid.
1808 SQL: ORDER BY clause is invalid.
1809 SQL: Out of memory.
1810 SQL: Invalid use of subquery.
1811 SQL: Aggregate on non-numeric expression.
1812 SQL: Statement too long.
1813 SQL: Use of UNION in subquery is invalid.
1814 SQL: Queries of this type are not supported.
1815 <cursor> must be created with SELECT ...INTO TABLE.
1818 SQL: FROM clause is required.
1819 SQL: DISTINCT is invalid.
1820 SQL: SELECT contains invalid *.
1822 SQL: Invalid aggregate field.
1825 SQL: Subquery is invalid.
1826 SQL: SELECT is invalid.
1828 SQL: Illegal GROUP BY in subquery.
1830 SQL: Index is not found.
1831 SQL: Error building temporary index.
1832 <field> | <variable> is not unique and must be qualified.
1833 SQL: WHERE clause is invalid.
1834 SQL: Too many UNIONs.
1839 SQL: Operation was canceled.
1841 SQL: Too many columns referenced.
1842 SQL: Subquery nesting is too deep.
1844 Cannot nest aggregate functions.
1845 SQL expression is too complex.
1903 String is too long to fit.
1907 Drive specifier is invalid.
1908 Length or decimal place argument is invalid.
1912 Operation is invalid for a General field.
1999 Function is not implemented.
Additional query words: VFoxWin
======================================================================
Keywords : kbvfp300 kbvfp600
Technology : kbVFPsearch kbAudDeveloper kbVFP300
Version : WINDOWS:3.0
=============================================================================
THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS
PROVIDED «AS IS» WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS
ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO
EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR
ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL,
CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF
MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION
OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES
SO THE FOREGOING LIMITATION MAY NOT APPLY.
Copyright Microsoft Corporation 1986-2002.
Генерирует ошибку Visual FoxPro.
Синтаксис:
ERROR nErrorNumber | nErrorNumber, cMessageText1 | [cMessageText2]
Параметры:
nErrorNumber
Задает номер ошибки, которую предстоит сгенерировать. Когда задан номер ошибки, будет использовано стандартное сообщение об ошибке Visual FoxPro. Список сообщений об ошибках Visual FoxPro с указанием их номеров приведен в теме Сообщения об ошибках в Техническом справочнике.
cMessageText1
Задает текст сообщения об ошибке, дающий о ней дополнительную информацию. Например, если вы ссылаетесь на несуществующую переменную памяти, Visual FoxPro подставит в сообщение об ошибке имя этой переменной памяти.
cMessageText2
Задает текст для сообщения об ошибке. Если аргумент cMessageText2 задан вместо nErrorNumber, генерируется ошибка Visual FoxPro номер 1098 (ошибка, определенная пользователем). Чтобы перенести часть сообщения на следующую строку, пользуйтесь в тексте cMessageText2 возвратом каретки (CHR(13)).
Комментарии:
Команду ERROR можно использовать для тестирования программ обработки ошибок или для формирования собственных сообщений об ошибках.
Если в момент выдачи команды ERROR действует программа обработки ошибок ON ERROR, Visual FoxPro выполнит эту программу ON ERROR. Если ошибка имеет место для объекта, выполняется событие Error этого объекта.
Если команда ERROR выдана из окна команд и при этом программа ON ERROR не действует, Visual FoxPro отобразит сообщение об ошибке. Если ERROR выдана в программе и ON ERROR не действует, Visual FoxPro отобразит сообщение об ошибке и даст возможность отменить программу, приостановить ее или проигнорировать ошибку.
Пример:
* В следующем примере генерируются три сообщения об ошибках. Первое * из них представляет собой сообщение об ошибке Visual FoxPro "Variable * not found" [Переменная не найдена] (номер ошибки 12). Второе сообщение * об ошибке также соответствует ошибке 12 и содержит имя переменной * Myvariable. Последнее сообщение об ошибке является пользовательским * (номер ошибки 1089), с текстом "My error message" [Мое сообщение об * ошибке]. ERROR 12 && Generates the Visual FoxPro error "Variable not found" ERROR 12, 'Myvariable' && Variable 'Myvariable' not found error ERROR 'My error message' && Generates 'My error message' error
Рассмотрим следующий код:
x = –5
a = Sqrt(x)
b = x * x
Поскольку в VFP параметр функции SQRT( ) не может быть меньше нуля, то при выполнении приведенного кода возникнет ошибка. При этом стандартный обработчик ошибок VFP прервет исполнение программы и выдаст показанное на рис. 7.1 сообщение.
Рис. 7.1. Обработка ошибки в VFP
Стандартный обработчик ошибок можно заменить пользовательским.
Команда
ON ERROR [Command]
задает команду Command, выполняемую при возникновении ошибки VFP.
Как правило, Command – это вызов пользовательской программы или процедуры.
После выполнения Command работа программы возобновляется со строки, следующей за строкой, содержащей ошибку. Правда, если процедура-обработчик ошибки имеет команду RETRY, то строка с ошибкой будет выполнена еще раз.
При использовании ON ERROR без параметра Command восстанавливается стандартный обработчик ошибок VFP.
Процедура-обработчик ошибки не должна содержать команду ON ERROR. Если же такая команда в ней все же присутствует, то восстанавливается стандартный обработчик ошибок VFP.
Чтобы локализовать и описать возникшую ошибку, в ее обрабатывающую процедуру можно передать значения описанных в табл. 7.3 функций.
Таблица 7.3
Функции для локализации и расшифровки ошибки
Функция |
Описание |
ERROR( ) |
Возвращает номер последней ошибки; результат либо передается процедуре-обработчику ошибки, указанной в команде ON ERROR, либо функция вызывается в этой процедуре. Соответствующее сообщение об ошибке возвращает функция MESSAGE( ) |
MESSAGE([1]) |
Возвращает, если вызвана без параметра, строку, содержащую описание ошибки. При вызове с параметром функция вернет текст, имеющийся в строке программного кода, в которой возникла ошибка. Вызов с параметром нельзя использовать, если при компиляции (команда COMPILE) использована опция NODEBUG |
LINENO([1]) |
Возвращает, если вызвана без параметра, номер строки с ошибкой относительно первой строки главной программы. При вызове с параметром функция вернет номер строки с ошибкой относительно первой строки текущего программного компонента. |
PROGRAM([nLevel]) |
Возвращает, если параметр nLevel опущен, имя выполняемой программы. В случае ошибки возвращает имя программы, в которой произошла ошибка. |
SYS(16 [, nLevel]) |
Аналогична функции PROGRAM( ), однако в отличие от последней возвращает вдобавок имя файла (с указанием пути), в котором расположена выполняемая процедура или функции. Имя файла не возвращается, если выполняемая программа является частью приложения. |
SYS(2018) |
Возвращает параметр, включаемый в строку сообщения об ошибке. Тип результата – символьный. |
Пример 1. Иллюстрируется работа команды ON ERROR на коде, имеющем 2 ошибки.
&& Очищаем окно VFP
clear
&& ErrorHandler – имя процедуры, обрабатывающей ошибки
on error do ErrorHandler with Error( ), Message( ), Message(1), Lineno( ), Program( ), Sys(16)
x = –5
&& Ошибка 1. Попытка извлечь корень из отрицательного числа
a = Sqrt(x)
&& Ошибка 2. Использование несуществующей переменной a
b = a * x
&& Восстанавливаем заданный по умолчанию обработчик ошибок
on error
procedure ErrorHandler
parameters err, mes, mes1, lineNumber, progName, fileName
if Set(‘TEXTMERGE’) = ‘OFF’
set textmerge on show
endif
&& Выводим дополнительно текст об ошибках в файл
set textmerge to d:a.txt additive
Номер ошибки: <<Transform(err)>>
Описание ошибки: <<mes>>
Локализация ошибки:
оператор: <<Upper(mes1)>>
номер строки: <<Transform(lineNumber)>>
имя программы: <<progName>>
имя файла: <<fileName>>
&& Закрываем файл, содержащий сообщения об ошибках
Fclose(_TEXT)
endProc
Сообщения, сгенерированные процедурой ErrorHandler:
Номер ошибки: 61
Описание ошибки: SQRT( ) argument cannot be negative
Локализация ошибки:
оператор: A = SQRT(X)
номер строки: 8
имя программы: TEST
имя файла: D: TEST.FXP
Номер ошибки: 12
Описание ошибки: Variable ‘A’ is not found
Локализация ошибки:
оператор: B = A * X
номер строки: 10
имя программы: TEST
имя файла: D: TEST.FXP
Пример 2. Печатаются значения элементов массива, сгенерированного функцией AERROR( ), при попытке добавить запись в таблицу Authors.dbf с недопустимым (отрицательным) значением поля AuthorId.
Встроим в таблицу Authors.dbf триггер вставки, содержащий указанное на рис. 7.2 выражение.
Рис. 7.2. Триггер вставки таблицы Authors.dbf
Выполним с тем же обработчиком ошибок следующий код:
clear
on error do ErrorHandler
close databases
open database ‘d:HomeLibraryHomeLibrary’
&& Открываем таблицу Authors.dbf, активизируя индекс AuthorId
use Authors order tag AuthorId
m.AuthorId = –123
m.Author = ‘Федоров Алексей Георгиевич’
m.InputDate = {^2005–01–01}
if not Seek(m.AuthorId)
insert into Authors from memvar
endif
on error
procedure ErrorHandler
&& Направляем сообщения в окно VFP и в файл d:a.txt
if Set(‘CONSOLE’) = ‘OFF’
set console on
endif
set alternate to d:a.txt additive
set alternate on
nRows = Aerror(aErrorArray)
for k = 1 to nRows
? ‘Номер ошибки: ‘, aErrorArray(k, 1)
? ‘Описание ошибки: ‘, aErrorArray(k, 2)
if not IsNull(aErrorArray(k, 3)) then
? ‘Параметр ошибки: ‘, aErrorArray(k, 3)
endif
if not IsNull(aErrorArray(k, 4)) then
? ‘Номер рабочей области: ‘, aErrorArray(k, 4)
Endif
if not IsNull(aErrorArray(k, 5)) then
do case
case aErrorArray(k, 5) = 1
? ‘Ошибка при добавлении данных’
case aErrorArray(k, 5) = 2
? ‘Ошибка при обновлении данных’
case aErrorArray(k, 5) = 3
? ‘Ошибка при удалении данных’
endCase
endif
endFor
&& Закрываем файл, содержащий сообщения об ошибках
set alternate to
endProc
Сообщения, сгенерированные процедурой ErrorHandler:
Номер ошибки: 1539
Описание ошибки: Trigger failed
Номер рабочей области: 1
Ошибка при добавлении данных
После обнаружения ошибки для ее обработки употребляются в том числе приведенные в табл. 7.4 команды.
Таблица 7.4
Команды CANCEL, RESUME, RETRY, RETURN и SUSPEND
Команда |
Описание |
CANCEL |
Прекращает исполнение текущей программы; все ее PRIVATE-переменные освобождаются |
RESUME |
Возобновляет исполнение приостановленной командой SUSPEND программы |
RETRY |
Повторно выполняет последнюю команду. Команда, в частности, полезна в процедурах, обрабатывающих ошибки, например, для повторного выполнения команды до тех пор, пока не выполнится успешно функция, блокирующая запись или таблицу. Управление процессом осуществляется командой SET REPROCESS, задающей число попыток или время, в течение которого блокировки ожидается снятие блокировки |
RETURN [eExpression |
Передает управление вызывающей программе, возвращая значение eExpression. Управление передается вызывающей программе верхнего уровня, если задана опции TO MASTER, или процедуре ProcedureName, если задана последняя опция команды. |
SUSPEND |
Приостанавливает выполнение текущей программы. После выполнения SUSPEND имеется возможность выполнить необходимые для прояснения ситуации действия: проверить значения переменных, открыть окно трассировки или отладки и т. д. Работа приостановленной программы возобновляется командой RESUME |
При необходимости сведения об ошибке можно очистить.
Команда
CLEAR ERROR
восстанавливает структуры VFP, употребляемые описания ошибки, в состояние, характерное для безошибочного функционирования приложения. При этом значения по умолчанию восстанавливаются для функций
AERROR( ) – будет возвращать 0;
ERROR( ) – будет возвращать 0;
MESSAGE( ), MESSAGE(1) и SYS(2018) – будут возвращать чистую строку.
Команду CLEAR ERROR нельзя употреблять внутри конструкции TRY … CATCH … FINALLY: объект-исключение после употребления CLEAR ERROR внутри конструкции может стать недоступным.