Program error 1407 prolog
Message:1407 Functor is not found in a domain (during term reading or converting)
Message:1407 Functor is not found in a domain (during term reading or converting)
Очень похоже на: автомобиль не едет!
В чем проблема? Вам перевести?
Как база создавалась?
Сравнивали объявление фактов базы с тем, что в файле базы?
Какие типы данных используются?
Ставьте себя на место тех, к кому Вы обращаетесь и кто будет читать.
domains
откуда, куда, рейс = string
время_отбытия = unsigned
время_прибытия = unsigned
день = unsigned
дата_начала,дата_окончания = unsigned
дни_недели = string
facts — route
nondeterm маршрут(откуда,куда,рейс,время_отбытия,время_прибы тия,день,дата_начала,дата_окончания,дни_недели)
clauses
маршрут(«ХЕЛЬСИНКИ»,»МОСКВА»,»204″,1110,1270,0,201 10225,20110302,»123567″).
find_route():-
existfile(«avia.dat»),
маршрут(X,_,_,_,_,_,_,_,_),
write(X),nl,
consult(«avia.dat»,route).
goal
existfile(«avia.dat») успешен
факт был взят из текста avia.dat.
ошибка выдается на consult(«avia.dat»,route).
Гм. Проблема Message:1407 Functor is not found in a domain (during term reading or converting) — проблема содержимого файла, а не его расширения (это я не shdu)))
И в сто-пицот-первый раз: ГРАЖДАНЕ, НАБИВАЙТЕ БАЗУ НЕПОСРЕДСТВЕННО В ПРОГЕ. В CLAUSES. ИБО ТАМ КОМПИЛЯТОР БУДЕТ ТЫКАТЬ НЕПОСРЕДСТВЕННО В ОШИБКИ. ЗАТЕМ ЗАПУСКАЙТЕ: goal save(. ). — И ОНО САМО СОЗДАСТ И ЗАЛЬЁТ ФАЙЛ РОВНО ТАК, КАК ЕМУ НАДО. ))))))))))))))))))))))))))))))))
буфер обмена довольно умный, он может и ЮНИКОДе держать и не только его, а вот редакторы могут ошибаться. Но чаще всего ошибается пользователь
файл для consult может быть и не ЮНИКОДный, а для ЮНИКОДа принято первые два байта специальные писАть. BOM
Источник
Program error 1407 prolog
10.5 Raising Prolog errors
The following functions allows a C function to raise a Prolog error. Refer to the section concerning Prolog errors for more information about the effect of raising an error (section 6.3).
10.5.1 Managing the error context
When one of the following error function is invoked it refers to the implicit error context (section 6.3.1). This context indicates the name and the arity of the concerned predicate. When using a foreign/2 declaration this context is set by default to the name and arity of the associated Prolog predicate. This can be controlled using the bip_name option (section 10.3.2). In any case, the following functions can also be used to modify this context:
The function Pl_Set_C_Bip_Name(functor, arity) initializes the context of the error with functor and arity (if arity functor is significant). The function Pl_Unset_C_Bip_Name() removes such an initialization (the context is then reset to the last Functor / Arity set by a call to set_bip_name/2 (section 8.22.3). This is useful when writing a C routine to define a context for errors occurring in this routine and, before exiting to restore the previous context.
10.5.2 Instantiation error
The following function raises an instantiation error (section 6.3.2):
10.5.3 Uninstantiation error
The following function raises an uninstantiation error (section 6.3.3):
void Pl_Err_Uninstantiation( PlTerm culprit)
10.5.4 Type error
The following function raises a type error (section 6.3.4):
void Pl_Err_Type(int atom_type, PlTerm culprit)
atom_type is (the internal key of) the atom associated with the expected type. For each type name T there is a corresponding predefined atom stored in a global variable whose name is of the form pl_type_ T . culprit is the argument which caused the error.
Example : x is an atom while an integer was expected: Pl_Err_Type(pl_type_integer, x) .
10.5.5 Domain error
The following function raises a domain error (section 6.3.5):
void Pl_Err_Domain(int atom_domain, PlTerm culprit)
atom_domain is (the internal key of) the atom associated with the expected domain. For each domain name D there is a corresponding predefined atom stored in a global variable whose name is of the form domain_ D . culprit is the argument which caused the error.
Example : x is Pl_Err_Domain(pl_domain_not_less_than_zero, x) .
10.5.6 Existence error
The following function raises an existence error (section 6.3.6):
void Pl_Err_Existence(int atom_object, PlTerm culprit)
atom_object is (the internal key of) the atom associated with the type of the object. For each object name O there is a corresponding predefined atom stored in a global variable whose name is of the form pl_existence_ O . culprit is the argument which caused the error.
Example : x does not refer to an existing source: Pl_Err_Existence(pl_existence_source_sink, x) .
10.5.7 Permission error
The following function raises a permission error (section 6.3.7):
void Pl_Err_Permission(int atom_operation, int atom_permission, PlTerm culprit)
atom_operation is (the internal key of) the atom associated with the operation which caused the error. For each operation name O there is a corresponding predefined atom stored in a global variable whose name is of the form pl_permission_operation_ O . atom_permission is (the internal key of) the atom associated with the tried permission. For each permission name P there is a corresponding predefined atom stored in a global variable whose name is of the form pl_permission_type_ P . culprit is the argument which caused the error.
Example : reading from an output stream x : Pl_Err_Permission(pl_permission_operation_input,
pl_permission_type_stream, x) .
10.5.8 Representation error
The following function raises a representation error (section 6.3.8):
void Pl_Err_Representation(int atom_limit)
atom_limit is (the internal key of) the atom associated with the reached limit. For each limit name L there is a corresponding predefined atom stored in a global variable whose name is of the form pl_representation_ L .
Example : an arity too big occurs: Pl_Err_Representation(pl_representation_max_arity) .
10.5.9 Evaluation error
The following function raises an evaluation error (section 6.3.9):
void Pl_Err_Evaluation(int atom_error)
atom_error is (the internal key of) the atom associated with the error. For each evaluation error name E there is a corresponding predefined atom stored in a global variable whose name is of the form pl_evaluation_ E .
Example : a division by zero occurs: Pl_Err_Evaluation(pl_evaluation_zero_divisor) .
10.5.10 Resource error
The following function raises a resource error (section 6.3.10):
void Pl_Err_Resource(int atom_resource)
atom_resource is (the internal key of) the atom associated with the resource. For each resource error name R there is a corresponding predefined atom stored in a global variable whose name is of the form pl_resource_ R .
Example : too many open streams: Pl_Err_Resource(pl_resource_too_many_open_streams) .
10.5.11 Syntax error
The following function raises a syntax error (section 6.3.11):
void Pl_Err_Syntax(int atom_error)
atom_error is (the internal key of) the atom associated with the error. There is no predefined syntax error atoms.
Example : a / is expected: Pl_Err_Syntax(Pl_Create_Atom(«/ expected»)) .
The following function emits a syntax error according to the value of the syntax_error Prolog flag (section 8.22.1). This function can then return (if the value of the flag is either warning or fail ). In that case the calling function should fail (e.g. returning PL_FALSE ). This function accepts a file name (the empty string C «» can be passed), a line and column number and an error message string. Using this function makes it possible to further call the built-in predicate syntax_error_info/4 (section 8.14.4):
void Pl_Emit_Syntax_Error(char *file_name, int line, int column, char *message)
Example : a / is expected: Pl_Emit_Syntax_Error(«data», 10, 30, «/ expected») .
10.5.12 System error
The following function raises a system error (4.3.11, page *):
void Pl_Err_System(int atom_error)
atom_error is (the internal key of) the atom associated with the error. There is no predefined system error atoms.
Example : an invalid pathname is given: Pl_Err_System(Pl_Create_Atom(«invalid path name»)) .
The following function emits a system error associated with an operating system error according to the value of the os_error Prolog flag (section 8.22.1). This function can then return (if the value of the flag is either warning or fail ). In that case the calling function should fail (e.g. returning PL_FALSE ).
The following function uses the value of the errno C library variable (basically it calls Pl_Err_System with the result of strerror(errno) ).
Example : if a call to the C Unix function chdir(2) returns -1 then call Os_Error() .
Copyright (C) 1999-2021 Daniel Diaz Verbatim copying and distribution of this entire article is permitted in any medium, provided this notice is preserved. More about the copyright
Источник
Program error 1407 prolog
The predicates catch/3 and throw/1 provide ISO compliant raising and catching of exceptions.
[ISO] catch( :Goal, +Catcher, :Recover ) Behaves as call/1 if no exception is raised when executing Goal . If an exception is raised using throw/1 while Goal executes, and the Goal is the innermost goal for which Catcher unifies with the argument of throw/1, all choice points generated by Goal are cut, the system backtracks to the start of catch/3 while preserving the thrown exception term, and Recover is called as in call/1.
The overhead of calling a goal through catch/3 is comparable to call/1. Recovery from an exception is much slower, especially if the exception term is large due to the copying thereof or is decorated with a stack trace using, e.g., the library library(prolog_stack) based on the prolog_exception_hook/4 hook predicate to rewrite exceptions.
[ISO] throw( +Exception ) Raise an exception. The system looks for the innermost catch/3 ancestor for which Exception unifies with the Catcher argument of the catch/3 call. See catch/3 for details.
ISO demands that throw/1 make a copy of Exception , walk up the stack to a catch/3 call, backtrack and try to unify the copy of Exception with Catcher . SWI-Prolog delays backtracking until it actually finds a matching catch/3 goal. The advantage is that we can start the debugger at the first possible location while preserving the entire exception context if there is no matching catch/3 goal. This approach can lead to different behaviour if Goal and Catcher of catch/3 call shared variables. We assume this to be highly unlikely and could not think of a scenario where this is useful. 79 I’d like to acknowledge Bart Demoen for his clarifications on these matters.
In addition to explicit calls to throw/1, many built-in predicates throw exceptions directly from C. If the Exception term cannot be copied due to lack of stack space, the following actions are tried in order:
- If the exception is of the form error(Formal, ImplementationDefined) , try to raise the exception without the ImplementationDefined part.
- Try to raise error( resource_error(stack) , global) .
- Abort (see abort/0).
If an exception is raised in a call-back from C (see chapter 12) and not caught in the same call-back, PL_next_solution() fails and the exception context can be retrieved using PL_exception().
catch_with_backtrace( :Goal, +Catcher, :Recover ) As catch/3, but if library library(prolog_stack) is loaded and an exception of the shape error(Format, Context) is raised Context is extended with a backtrace. To catch an error and print its message including a backtrace, use the following template:
This is good practice for a catch-all wrapper around an application. See also main/0 from library library(main) .
4.10.1 Urgency of exceptions
Under some conditions an exception may be raised as a result of handling another exception. Below are some of the scenarios:
- The predicate setup_call_cleanup/3 calls the cleanup handler as a result of an exception and the cleanup handler raises an exception itself. In this case the most urgent exception is propagated into the environment.
- Raising an exception fails due to lack of resources, e.g., lack of stack space to store the exception. In this case a resource exception is raised. If that too fails the system tries to raise a resource exception without (stack) context. If that fails it will raise the exception ‘$aborted’ , also raised by abort/0. As no stack space is required for processing this atomic exception, this should always succeed.
- Certain callback operations raise an exception while processing another exception or a previous callback already raised an exception before there was an opportunity to process the exception. The most notable callback subject to this issue are prolog_event_hook/1 (supporting e.g., the graphical debugger), prolog_exception_hook/4 (rewriting exceptions, e.g., by adding context) and print_message/2 when called from the core facilities such as the internal debugger. As with setup_call_cleanup/3, the most urgent exception is preserved.
If the most urgent exceptions needs to be preserved, the following exception ordering is respected, preserving the topmost matching error.
- ‘$aborted’ (abort/0)
- time_limit_exceeded (call_with_time_limit/2)
- error( resource_error(Resource) , Context)
- error(Formal, Context)
- All other exceptions
Note The above resolution is not described in the ISO standard. This is not needed either because ISO does not specify setup_call_cleanup/3 and does not deal with environment management issues such as (debugger) callbacks. Neither does it define abort/0 or timeout handling. Notably abort/0 and timeout are non-logical control structures. They are implemented on top of exceptions as they need to unwind the stack, destroy choice points and call cleanup handlers in the same way. However, the pending exception should not be replaced by another one before the intended handler is reached. The abort exception cannot be caught, something which is achieved by wrapping the cleanup handler of catch/3 into call_cleanup(Handler, abort) .
4.10.2 Debugging and exceptions
Before the introduction of exceptions in SWI-Prolog a runtime error was handled by printing an error message, after which the predicate failed. If the Prolog flag debug_on_error was in effect (default), the tracer was switched on. The combination of the error message and trace information is generally sufficient to locate the error.
With exception handling, things are different. A programmer may wish to trap an exception using catch/3 to avoid it reaching the user. If the exception is not handled by user code, the interactive top level will trap it to prevent termination.
If we do not take special precautions, the context information associated with an unexpected exception (i.e., a programming error) is lost. Therefore, if an exception is raised which is not caught using catch/3 and the top level is running, the error will be printed, and the system will enter trace mode.
If the system is in a non-interactive call-back from foreign code and there is no catch/3 active in the current context, it cannot determine whether or not the exception will be caught by the external routine calling Prolog. It will then base its behaviour on the Prolog flag debug_on_error:
- current_prolog_flag(debug_on_error, false)
The exception does not trap the debugger and is returned to the foreign routine calling Prolog, where it can be accessed using PL_exception(). This is the default. - current_prolog_flag(debug_on_error, true)
If the exception is not caught by Prolog in the current context, it will trap the tracer to help analyse the context of the error.
While looking for the context in which an exception takes place, it is advised to switch on debug mode using the predicate debug/0. The hook prolog_exception_hook/4 can be used to add more debugging facilities to exceptions. An example is the library library(http/http_error) , generating a full stack trace on errors in the HTTP server library.
4.10.3 The exception term
4.10.3.1 General form of the ISO standard exception term
The predicate throw/1 takes a single argument, the exception term, and the ISO standard stipulates that the exception term be of the form error(Formal, Context) with:
- Formal
the‘formal’ description of the error, as listed in chapter 7.12.2 pp. 62-63 («Error classification») of the ISO standard. It indicates the error class and possibly relevant error context information. It may be a compound term of arity 1,2 or 3 — or simply an atom if there is no relevant error context information.
additional context information beyond the one in Formal . If may be unset, i.e. a fresh variable, or set to something that hopefully will help the programmer in debugging. The structure of Context is left unspecified by the ISO Standard, so SWI-Prolog creates it own convention (see below).
Thus, constructing an error term and throwing it might take this form (although you would not use the illustrative explicit naming given here; instead composing the exception term directly in a one-liner):
Note that the ISO standard formal term expresses what should be the case or what is the expected correct state, and not what is the problem. For example:
- If a variable is found to be uninstantiated but should be instantiated, the error term is instantiation_error : The problem is not that there is an unwanted instantiation, but that the correct state is the one with an instantiated variable.
In case a variable is found to be instantiated but should be uninstantiated (because it will be used for output), the error term is uninstantiation_error(Culprit) : The problem is not that there is lack of instantiation, but that the correct state is the one which Culprit (or one of its subterms) is more uninstantiated than is the case.
4.10.3.2 Throwing exceptions from applications and libraries
User predicates are free to choose the structure of their exception terms (i.e., they can define their own conventions) but should adhere to the ISO standard if possible, in particular for libraries.
Notably, exceptions of the shape error(Formal,Context) are recognised by the development tools and therefore expressing unexpected situations using these exceptions improves the debugging experience.
In SWI-Prolog, the second argument of the exception term, i.e., the Context argument, is generally of the form context(Location, Message) , where:
- Location
describes the execution context in which the exception occurred. While the Location argument may be specified as a predicate indicator ( Name / Arity ), it is typically filled by the library(prolog_stack) library. This library recognises uncaught errors or errors caught by catch_with_backtrace/3 and fills the Location argument with a backtrace.
provides an additional description of the error or can be left as a fresh variable if there is nothing appropriate to fill in.
ISO standard exceptions can be thrown via the predicates exported from library(error) . Termwise, these predicates look exactly like the Formal of the ISO standard error term they throw:
Источник
Содержание
- Program error 1407 пролог
- Program error 1407 пролог
- 4.10.1 Urgency of exceptions
- 4.10.2 Debugging and exceptions
- 4.10.3 The exception term
- 4.10.3.1 General form of the ISO standard exception term
- 4.10.3.2 Throwing exceptions from applications and libraries
- Program error 1407 пролог
- 4.10.1 Urgency of exceptions
- 4.10.2 Debugging and exceptions
- 4.10.3 The exception term
- 4.10.3.1 General form of the ISO standard exception term
- 4.10.3.2 Throwing exceptions from applications and libraries
Program error 1407 пролог
Message:1407 Functor is not found in a domain (during term reading or converting)
Message:1407 Functor is not found in a domain (during term reading or converting)
Очень похоже на: автомобиль не едет!
В чем проблема? Вам перевести?
Как база создавалась?
Сравнивали объявление фактов базы с тем, что в файле базы?
Какие типы данных используются?
Ставьте себя на место тех, к кому Вы обращаетесь и кто будет читать.
domains
откуда, куда, рейс = string
время_отбытия = unsigned
время_прибытия = unsigned
день = unsigned
дата_начала,дата_окончания = unsigned
дни_недели = string
facts — route
nondeterm маршрут(откуда,куда,рейс,время_отбытия,время_прибы тия,день,дата_начала,дата_окончания,дни_недели)
clauses
маршрут(«ХЕЛЬСИНКИ»,»МОСКВА»,»204″,1110,1270,0,201 10225,20110302,»123567″).
find_route():-
existfile(«avia.dat»),
маршрут(X,_,_,_,_,_,_,_,_),
write(X),nl,
consult(«avia.dat»,route).
goal
existfile(«avia.dat») успешен
факт был взят из текста avia.dat.
ошибка выдается на consult(«avia.dat»,route).
Гм. Проблема Message:1407 Functor is not found in a domain (during term reading or converting) — проблема содержимого файла, а не его расширения (это я не shdu)))
И в сто-пицот-первый раз: ГРАЖДАНЕ, НАБИВАЙТЕ БАЗУ НЕПОСРЕДСТВЕННО В ПРОГЕ. В CLAUSES. ИБО ТАМ КОМПИЛЯТОР БУДЕТ ТЫКАТЬ НЕПОСРЕДСТВЕННО В ОШИБКИ. ЗАТЕМ ЗАПУСКАЙТЕ: goal save(. ). — И ОНО САМО СОЗДАСТ И ЗАЛЬЁТ ФАЙЛ РОВНО ТАК, КАК ЕМУ НАДО. ))))))))))))))))))))))))))))))))
буфер обмена довольно умный, он может и ЮНИКОДе держать и не только его, а вот редакторы могут ошибаться. Но чаще всего ошибается пользователь
файл для consult может быть и не ЮНИКОДный, а для ЮНИКОДа принято первые два байта специальные писАть. BOM
Источник
Program error 1407 пролог
The predicates catch/3 and throw/1 provide ISO compliant raising and catching of exceptions.
[ISO] catch( :Goal, +Catcher, :Recover ) Behaves as call/1 if no exception is raised when executing Goal . If an exception is raised using throw/1 while Goal executes, and the Goal is the innermost goal for which Catcher unifies with the argument of throw/1, all choice points generated by Goal are cut, the system backtracks to the start of catch/3 while preserving the thrown exception term, and Recover is called as in call/1.
The overhead of calling a goal through catch/3 is comparable to call/1. Recovery from an exception is much slower, especially if the exception term is large due to the copying thereof or is decorated with a stack trace using, e.g., the library library(prolog_stack) based on the prolog_exception_hook/4 hook predicate to rewrite exceptions.
[ISO] throw( +Exception ) Raise an exception. The system looks for the innermost catch/3 ancestor for which Exception unifies with the Catcher argument of the catch/3 call. See catch/3 for details.
ISO demands that throw/1 make a copy of Exception , walk up the stack to a catch/3 call, backtrack and try to unify the copy of Exception with Catcher . SWI-Prolog delays backtracking until it actually finds a matching catch/3 goal. The advantage is that we can start the debugger at the first possible location while preserving the entire exception context if there is no matching catch/3 goal. This approach can lead to different behaviour if Goal and Catcher of catch/3 call shared variables. We assume this to be highly unlikely and could not think of a scenario where this is useful. 79 I’d like to acknowledge Bart Demoen for his clarifications on these matters.
In addition to explicit calls to throw/1, many built-in predicates throw exceptions directly from C. If the Exception term cannot be copied due to lack of stack space, the following actions are tried in order:
- If the exception is of the form error(Formal, ImplementationDefined) , try to raise the exception without the ImplementationDefined part.
- Try to raise error( resource_error(stack) , global) .
- Abort (see abort/0).
If an exception is raised in a call-back from C (see chapter 12) and not caught in the same call-back, PL_next_solution() fails and the exception context can be retrieved using PL_exception().
catch_with_backtrace( :Goal, +Catcher, :Recover ) As catch/3, but if library library(prolog_stack) is loaded and an exception of the shape error(Format, Context) is raised Context is extended with a backtrace. To catch an error and print its message including a backtrace, use the following template:
This is good practice for a catch-all wrapper around an application. See also main/0 from library library(main) .
4.10.1 Urgency of exceptions
Under some conditions an exception may be raised as a result of handling another exception. Below are some of the scenarios:
- The predicate setup_call_cleanup/3 calls the cleanup handler as a result of an exception and the cleanup handler raises an exception itself. In this case the most urgent exception is propagated into the environment.
- Raising an exception fails due to lack of resources, e.g., lack of stack space to store the exception. In this case a resource exception is raised. If that too fails the system tries to raise a resource exception without (stack) context. If that fails it will raise the exception ‘$aborted’ , also raised by abort/0. As no stack space is required for processing this atomic exception, this should always succeed.
- Certain callback operations raise an exception while processing another exception or a previous callback already raised an exception before there was an opportunity to process the exception. The most notable callback subject to this issue are prolog_event_hook/1 (supporting e.g., the graphical debugger), prolog_exception_hook/4 (rewriting exceptions, e.g., by adding context) and print_message/2 when called from the core facilities such as the internal debugger. As with setup_call_cleanup/3, the most urgent exception is preserved.
If the most urgent exceptions needs to be preserved, the following exception ordering is respected, preserving the topmost matching error.
- ‘$aborted’ (abort/0)
- time_limit_exceeded (call_with_time_limit/2)
- error( resource_error(Resource) , Context)
- error(Formal, Context)
- All other exceptions
Note The above resolution is not described in the ISO standard. This is not needed either because ISO does not specify setup_call_cleanup/3 and does not deal with environment management issues such as (debugger) callbacks. Neither does it define abort/0 or timeout handling. Notably abort/0 and timeout are non-logical control structures. They are implemented on top of exceptions as they need to unwind the stack, destroy choice points and call cleanup handlers in the same way. However, the pending exception should not be replaced by another one before the intended handler is reached. The abort exception cannot be caught, something which is achieved by wrapping the cleanup handler of catch/3 into call_cleanup(Handler, abort) .
4.10.2 Debugging and exceptions
Before the introduction of exceptions in SWI-Prolog a runtime error was handled by printing an error message, after which the predicate failed. If the Prolog flag debug_on_error was in effect (default), the tracer was switched on. The combination of the error message and trace information is generally sufficient to locate the error.
With exception handling, things are different. A programmer may wish to trap an exception using catch/3 to avoid it reaching the user. If the exception is not handled by user code, the interactive top level will trap it to prevent termination.
If we do not take special precautions, the context information associated with an unexpected exception (i.e., a programming error) is lost. Therefore, if an exception is raised which is not caught using catch/3 and the top level is running, the error will be printed, and the system will enter trace mode.
If the system is in a non-interactive call-back from foreign code and there is no catch/3 active in the current context, it cannot determine whether or not the exception will be caught by the external routine calling Prolog. It will then base its behaviour on the Prolog flag debug_on_error:
- current_prolog_flag(debug_on_error, false)
The exception does not trap the debugger and is returned to the foreign routine calling Prolog, where it can be accessed using PL_exception(). This is the default. - current_prolog_flag(debug_on_error, true)
If the exception is not caught by Prolog in the current context, it will trap the tracer to help analyse the context of the error.
While looking for the context in which an exception takes place, it is advised to switch on debug mode using the predicate debug/0. The hook prolog_exception_hook/4 can be used to add more debugging facilities to exceptions. An example is the library library(http/http_error) , generating a full stack trace on errors in the HTTP server library.
4.10.3 The exception term
4.10.3.1 General form of the ISO standard exception term
The predicate throw/1 takes a single argument, the exception term, and the ISO standard stipulates that the exception term be of the form error(Formal, Context) with:
- Formal
the‘formal’ description of the error, as listed in chapter 7.12.2 pp. 62-63 («Error classification») of the ISO standard. It indicates the error class and possibly relevant error context information. It may be a compound term of arity 1,2 or 3 — or simply an atom if there is no relevant error context information.
additional context information beyond the one in Formal . If may be unset, i.e. a fresh variable, or set to something that hopefully will help the programmer in debugging. The structure of Context is left unspecified by the ISO Standard, so SWI-Prolog creates it own convention (see below).
Thus, constructing an error term and throwing it might take this form (although you would not use the illustrative explicit naming given here; instead composing the exception term directly in a one-liner):
Note that the ISO standard formal term expresses what should be the case or what is the expected correct state, and not what is the problem. For example:
- If a variable is found to be uninstantiated but should be instantiated, the error term is instantiation_error : The problem is not that there is an unwanted instantiation, but that the correct state is the one with an instantiated variable.
In case a variable is found to be instantiated but should be uninstantiated (because it will be used for output), the error term is uninstantiation_error(Culprit) : The problem is not that there is lack of instantiation, but that the correct state is the one which Culprit (or one of its subterms) is more uninstantiated than is the case.
4.10.3.2 Throwing exceptions from applications and libraries
User predicates are free to choose the structure of their exception terms (i.e., they can define their own conventions) but should adhere to the ISO standard if possible, in particular for libraries.
Notably, exceptions of the shape error(Formal,Context) are recognised by the development tools and therefore expressing unexpected situations using these exceptions improves the debugging experience.
In SWI-Prolog, the second argument of the exception term, i.e., the Context argument, is generally of the form context(Location, Message) , where:
- Location
describes the execution context in which the exception occurred. While the Location argument may be specified as a predicate indicator ( Name / Arity ), it is typically filled by the library(prolog_stack) library. This library recognises uncaught errors or errors caught by catch_with_backtrace/3 and fills the Location argument with a backtrace.
provides an additional description of the error or can be left as a fresh variable if there is nothing appropriate to fill in.
ISO standard exceptions can be thrown via the predicates exported from library(error) . Termwise, these predicates look exactly like the Formal of the ISO standard error term they throw:
Источник
Program error 1407 пролог
The predicates catch/3 and throw/1 provide ISO compliant raising and catching of exceptions.
[ISO] catch( :Goal, +Catcher, :Recover ) Behaves as call/1 if no exception is raised when executing Goal . If an exception is raised using throw/1 while Goal executes, and the Goal is the innermost goal for which Catcher unifies with the argument of throw/1, all choice points generated by Goal are cut, the system backtracks to the start of catch/3 while preserving the thrown exception term, and Recover is called as in call/1.
The overhead of calling a goal through catch/3 is comparable to call/1. Recovery from an exception is much slower, especially if the exception term is large due to the copying thereof or is decorated with a stack trace using, e.g., the library library(prolog_stack) based on the prolog_exception_hook/4 hook predicate to rewrite exceptions.
[ISO] throw( +Exception ) Raise an exception. The system looks for the innermost catch/3 ancestor for which Exception unifies with the Catcher argument of the catch/3 call. See catch/3 for details.
ISO demands that throw/1 make a copy of Exception , walk up the stack to a catch/3 call, backtrack and try to unify the copy of Exception with Catcher . SWI-Prolog delays backtracking until it actually finds a matching catch/3 goal. The advantage is that we can start the debugger at the first possible location while preserving the entire exception context if there is no matching catch/3 goal. This approach can lead to different behaviour if Goal and Catcher of catch/3 call shared variables. We assume this to be highly unlikely and could not think of a scenario where this is useful. 79 I’d like to acknowledge Bart Demoen for his clarifications on these matters.
In addition to explicit calls to throw/1, many built-in predicates throw exceptions directly from C. If the Exception term cannot be copied due to lack of stack space, the following actions are tried in order:
- If the exception is of the form error(Formal, ImplementationDefined) , try to raise the exception without the ImplementationDefined part.
- Try to raise error( resource_error(stack) , global) .
- Abort (see abort/0).
If an exception is raised in a call-back from C (see chapter 12) and not caught in the same call-back, PL_next_solution() fails and the exception context can be retrieved using PL_exception().
catch_with_backtrace( :Goal, +Catcher, :Recover ) As catch/3, but if library library(prolog_stack) is loaded and an exception of the shape error(Format, Context) is raised Context is extended with a backtrace. To catch an error and print its message including a backtrace, use the following template:
This is good practice for a catch-all wrapper around an application. See also main/0 from library library(main) .
4.10.1 Urgency of exceptions
Under some conditions an exception may be raised as a result of handling another exception. Below are some of the scenarios:
- The predicate setup_call_cleanup/3 calls the cleanup handler as a result of an exception and the cleanup handler raises an exception itself. In this case the most urgent exception is propagated into the environment.
- Raising an exception fails due to lack of resources, e.g., lack of stack space to store the exception. In this case a resource exception is raised. If that too fails the system tries to raise a resource exception without (stack) context. If that fails it will raise the exception ‘$aborted’ , also raised by abort/0. As no stack space is required for processing this atomic exception, this should always succeed.
- Certain callback operations raise an exception while processing another exception or a previous callback already raised an exception before there was an opportunity to process the exception. The most notable callback subject to this issue are prolog_event_hook/1 (supporting e.g., the graphical debugger), prolog_exception_hook/4 (rewriting exceptions, e.g., by adding context) and print_message/2 when called from the core facilities such as the internal debugger. As with setup_call_cleanup/3, the most urgent exception is preserved.
If the most urgent exceptions needs to be preserved, the following exception ordering is respected, preserving the topmost matching error.
- ‘$aborted’ (abort/0)
- time_limit_exceeded (call_with_time_limit/2)
- error( resource_error(Resource) , Context)
- error(Formal, Context)
- All other exceptions
Note The above resolution is not described in the ISO standard. This is not needed either because ISO does not specify setup_call_cleanup/3 and does not deal with environment management issues such as (debugger) callbacks. Neither does it define abort/0 or timeout handling. Notably abort/0 and timeout are non-logical control structures. They are implemented on top of exceptions as they need to unwind the stack, destroy choice points and call cleanup handlers in the same way. However, the pending exception should not be replaced by another one before the intended handler is reached. The abort exception cannot be caught, something which is achieved by wrapping the cleanup handler of catch/3 into call_cleanup(Handler, abort) .
4.10.2 Debugging and exceptions
Before the introduction of exceptions in SWI-Prolog a runtime error was handled by printing an error message, after which the predicate failed. If the Prolog flag debug_on_error was in effect (default), the tracer was switched on. The combination of the error message and trace information is generally sufficient to locate the error.
With exception handling, things are different. A programmer may wish to trap an exception using catch/3 to avoid it reaching the user. If the exception is not handled by user code, the interactive top level will trap it to prevent termination.
If we do not take special precautions, the context information associated with an unexpected exception (i.e., a programming error) is lost. Therefore, if an exception is raised which is not caught using catch/3 and the top level is running, the error will be printed, and the system will enter trace mode.
If the system is in a non-interactive call-back from foreign code and there is no catch/3 active in the current context, it cannot determine whether or not the exception will be caught by the external routine calling Prolog. It will then base its behaviour on the Prolog flag debug_on_error:
- current_prolog_flag(debug_on_error, false)
The exception does not trap the debugger and is returned to the foreign routine calling Prolog, where it can be accessed using PL_exception(). This is the default. - current_prolog_flag(debug_on_error, true)
If the exception is not caught by Prolog in the current context, it will trap the tracer to help analyse the context of the error.
While looking for the context in which an exception takes place, it is advised to switch on debug mode using the predicate debug/0. The hook prolog_exception_hook/4 can be used to add more debugging facilities to exceptions. An example is the library library(http/http_error) , generating a full stack trace on errors in the HTTP server library.
4.10.3 The exception term
4.10.3.1 General form of the ISO standard exception term
The predicate throw/1 takes a single argument, the exception term, and the ISO standard stipulates that the exception term be of the form error(Formal, Context) with:
- Formal
the‘formal’ description of the error, as listed in chapter 7.12.2 pp. 62-63 («Error classification») of the ISO standard. It indicates the error class and possibly relevant error context information. It may be a compound term of arity 1,2 or 3 — or simply an atom if there is no relevant error context information.
additional context information beyond the one in Formal . If may be unset, i.e. a fresh variable, or set to something that hopefully will help the programmer in debugging. The structure of Context is left unspecified by the ISO Standard, so SWI-Prolog creates it own convention (see below).
Thus, constructing an error term and throwing it might take this form (although you would not use the illustrative explicit naming given here; instead composing the exception term directly in a one-liner):
Note that the ISO standard formal term expresses what should be the case or what is the expected correct state, and not what is the problem. For example:
- If a variable is found to be uninstantiated but should be instantiated, the error term is instantiation_error : The problem is not that there is an unwanted instantiation, but that the correct state is the one with an instantiated variable.
In case a variable is found to be instantiated but should be uninstantiated (because it will be used for output), the error term is uninstantiation_error(Culprit) : The problem is not that there is lack of instantiation, but that the correct state is the one which Culprit (or one of its subterms) is more uninstantiated than is the case.
4.10.3.2 Throwing exceptions from applications and libraries
User predicates are free to choose the structure of their exception terms (i.e., they can define their own conventions) but should adhere to the ISO standard if possible, in particular for libraries.
Notably, exceptions of the shape error(Formal,Context) are recognised by the development tools and therefore expressing unexpected situations using these exceptions improves the debugging experience.
In SWI-Prolog, the second argument of the exception term, i.e., the Context argument, is generally of the form context(Location, Message) , where:
- Location
describes the execution context in which the exception occurred. While the Location argument may be specified as a predicate indicator ( Name / Arity ), it is typically filled by the library(prolog_stack) library. This library recognises uncaught errors or errors caught by catch_with_backtrace/3 and fills the Location argument with a backtrace.
provides an additional description of the error or can be left as a fresh variable if there is nothing appropriate to fill in.
ISO standard exceptions can be thrown via the predicates exported from library(error) . Termwise, these predicates look exactly like the Formal of the ISO standard error term they throw:
Источник
Smelov 1 / 1 / 0 Регистрация: 08.03.2011 Сообщений: 101 |
||||
1 |
||||
Не работает пример с динамической базой фактов14.03.2011, 13:22. Показов 8598. Ответов 8 Метки нет (Все метки)
Мне необходимо считать из файла вопросы и выводить их на экран. Для начала решил разобрать этот пример:
но он почему-то не работает, хотя вроде все правильно
__________________
1 |
Заблокирован |
|
14.03.2011, 14:31 |
2 |
Твой пример просто ждет,пока введешь с клавиатуры 5 чисел и все!Надо,как я понял из внешнего файла считывать вопросы,хранящиеся там как факты?
2 |
1 / 1 / 0 Регистрация: 08.03.2011 Сообщений: 101 |
|
14.03.2011, 14:56 [ТС] |
3 |
Твой пример просто ждет,пока введешь с клавиатуры 5 чисел и все!Надо,как я понял из внешнего файла считывать вопросы,хранящиеся там как факты? да, именно так!
0 |
Заблокирован |
||||
14.03.2011, 16:13 |
4 |
|||
Если закинуть все вопросы в файл с расширением .Dba, то твою проблему, учитывая предыдущий вопрос,можно решить так:
Ку-ку…
2 |
Smelov 1 / 1 / 0 Регистрация: 08.03.2011 Сообщений: 101 |
||||
14.03.2011, 16:45 [ТС] |
5 |
|||
Если закинуть все вопросы в файл с расширением .Dba, то твою проблему, учитывая предыдущий вопрос,можно решить так:
Ку-ку… Несколько вопросов:
0 |
Заблокирован |
|
14.03.2011, 19:08 |
6 |
Факты набираются в Блокноте,и сохраняются, но не как текстовый файл,а как произвольный с расширением .dba. Касаемо остальных ошибок-я работаю в Visual Prolog 5.2,у меня все работает.Если работаешь в Турбо Прологе,то вместо facts нужно писать database.
1 |
1 / 1 / 0 Регистрация: 08.03.2011 Сообщений: 101 |
|
14.03.2011, 20:57 [ТС] |
7 |
Факты набираются в Блокноте,и сохраняются, но не как текстовый файл,а как произвольный с расширением .dba. Касаемо остальных ошибок-я работаю в Visual Prolog 5.2,у меня все работает.Если работаешь в Турбо Прологе,то вместо facts нужно писать database. У меня тоже VIP 5.2… могу вставить скриншот. получается файл dba выглядит примерно так: Вопрос1 Добавлено через 52 минуты Однако теперь при запуске выдает следующее: PROGRAM ERROR. Module:VIP52BINWIN32QWERTY.PRO Pos:303 Очевидно, ошибка при чтении. В файле baza.dba записано следующее: Вопрос1
0 |
Заблокирован |
|
14.03.2011, 21:10 |
8 |
В файле baza.dba должно быть так написано:
1 |
1 / 1 / 0 Регистрация: 08.03.2011 Сообщений: 101 |
|
14.03.2011, 21:24 [ТС] |
9 |
В файле baza.dba должно быть так написано: Спасибо! теперь дошло!
0 |
|
||||||
Название | Автор | Ответов | Просмотров | Обновление | ||
шахматная задача на турбо прологе [?] |
GansEast | 0 | 2229 |
27.4.2012, 02:58 Автор: GansEast |
||
Задача на строки [?] строки, удаление, повтор |
botasa | 0 | 2418 |
13.4.2012, 18:01 Автор: botasa |
||
Need HELP [?] Prolog program |
4NcieN2 | 0 | 2857 |
1.4.2012, 05:14 Автор: 4NcieN2 |
||
Найти количество не парных чисел [?] |
katerinaа | 0 | 3760 |
20.3.2012, 10:02 Автор: katerinaа |
||
Найти значение переменной [?] |
katerinaа | 0 | 2227 |
20.3.2012, 10:00 Автор: katerinaа |
||
Prolog Editor для NetBeans [?] |
tumanovalex | 0 | 4300 |
3.2.2012, 11:58 Автор: tumanovalex |
||
Немного исправить код [?] sum_tree( T, Sum) true если Sum = сум Т |
DomSmile | 1 | 3829 |
30.12.2011, 12:49 Автор: DomSmile |
||
Не могу разобраться с терминами [?] |
Alexey91 | 0 | 2646 |
29.12.2011, 19:06 Автор: Alexey91 |
||
Вычисление n-го члена ряда [?] |
DunhiL11 | 2 | 3376 |
26.12.2011, 05:21 Автор: craua |
||
Помогите! [?] задача с графами. |
FeaTea | 0 | 2781 |
25.12.2011, 09:24 Автор: FeaTea |
||
деревья в прологе [?] поиск пути к элементу |
CraZzZyk | 14 | 5349 |
23.12.2011, 22:18 Автор: CraZzZyk |
||
[swi] Описать Findall. [?] |
АнастасияР | 0 | 2726 |
23.12.2011, 19:29 Автор: АнастасияР |
||
Завтра экзамен помогите решыть задания [?] |
sanyok20000 | 0 | 2562 |
23.12.2011, 17:20 Автор: sanyok20000 |
||
путь по дереву [?] прорисовка дерева |
CraZzZyk | 0 | 2568 |
22.12.2011, 22:35 Автор: CraZzZyk |
||
Символ встречающийся в списке наибольшее число раз [?] |
Nastassja | 0 | 2518 |
20.12.2011, 20:17 Автор: Nastassja |
||
Символьное интегрирование [?] |
Vovulya | 5 | 3518 |
19.12.2011, 19:45 Автор: Фантом |
||
Попадание в заштрихованную область [?] |
DunhiL11 | 1 | 4856 |
19.12.2011, 19:38 Автор: Фантом |
||
Задачи на Trubo Prolog. Решите за плату [?] |
DunhiL11 | 0 | 2329 |
19.12.2011, 17:01 Автор: DunhiL11 |
||
[SWI] поменять диагонали квадратной матрицы [?] |
sweetdream | 0 | 3043 |
19.12.2011, 10:54 Автор: sweetdream |
||
Список, элементы которого – непустые бинарные дере [?] |
aki295 | 0 | 3171 |
18.12.2011, 15:12 Автор: aki295 |
||
Логическая задача на Turbo / Visual Prolog! [?] =( нужен код, я полный ноль |
mmaker | 0 | 3508 |
7.12.2011, 11:45 Автор: mmaker |
||
Советы по планированию воздушного путешествия [?] Реализовать на Visual Prolog 5.2 |
Евгенияяяя | 1 | 2531 |
5.12.2011, 21:36 Автор: Евгенияяяя |
||
Логическая задача на Prolog [?] |
flogiston | 1 | 5741 |
5.12.2011, 14:53 Автор: alina2011 |
||
Работа со списками(циклическая) [?] |
kasperr | 2 | 2388 |
25.11.2011, 14:14 Автор: kasperr |
||
Задача — приложение списков, средства упр. док-вом [?] |
Takushika | 0 | 1708 |
23.11.2011, 21:59 Автор: Takushika |
||
Задача на обработку списков [?] определение среднего значения элементов |
Takushika | 0 | 1705 |
23.11.2011, 21:55 Автор: Takushika |
||
Поиск информации в базе данных [?] Поправьте готовую программу |
fenix63 | 0 | 3288 |
22.11.2011, 19:03 Автор: fenix63 |
||
Prolog [?] Родственные отношения |
Sevil | 0 | 1753 |
21.11.2011, 18:15 Автор: Sevil |
||
Итеративный алгоритм [?] |
flogiston | 0 | 1948 |
21.11.2011, 16:50 Автор: flogiston |
||
задача на прологе [?] нужна помощь в написании кода программы |
alexey1944 | 1 | 1812 |
17.11.2011, 09:46 Автор: alexey1944 |
||
сортировка списка [?] |
good1986 | 0 | 1832 |
9.11.2011, 21:25 Автор: good1986 |
||
Сумма ряда [?] |
flogiston | 2 | 3686 |
7.11.2011, 10:19 Автор: flogiston |
||
непонятная ошибка [?] error 1407 |
redwhite90 | 1 | 1795 |
6.11.2011, 02:56 Автор: redwhite90 |
||
Prolog. Путь от корня дерева, к указанному элемент [?] |
ROKI | 5 | 3912 |
31.10.2011, 01:57 Автор: Фантом |
||
ханойские башни [?] |
redwhite90 | 2 | 2043 |
30.10.2011, 12:22 Автор: redwhite90 |
||
swi prolog,пара задач [?] нужна помощь |
stan90 | 1 | 2275 |
29.10.2011, 13:47 Автор: Фантом |
||
Пролог поиск в ширину [?] |
lolli | 0 | 4316 |
20.10.2011, 22:55 Автор: lolli |
||
Упростить программочку [?] |
lolli | 0 | 1996 |
17.10.2011, 21:29 Автор: lolli |
||
Логическая задача про лошадей [?] |
ТаняСВ | 0 | 2790 |
13.10.2011, 21:28 Автор: ТаняСВ |
||
Помогите!) [?] объяснить решенную задачу |
alexey1944 | 2 | 1694 |
12.10.2011, 20:04 Автор: alexey1944 |
||
0 Чел. просматривают этот форум (0 Гостей, 0 Скрытых пользователей) | ||||||
0 Пользователей: | ||||||
Отображено 40 из 455 тем отсортировано по в за |
Topic: [SOLVED] TTaskdialog -> console app : error 1407 (Read 2830 times)
Hi all,
I was thinking to create a little application that calls the TTaskdialog. It might seem foolish doing it like this but the objective was to send the command + parameters from another program, then write the output to a file, file back into other program, done.
First test crashes with error:
-
Failed to create win32 control, error 1407
So it needs a windows something ??
This is my initial setup (I might be totally wrong too about this)
-
program msgdlg2;
-
{$mode objfpc}{$H+}
-
uses
-
Classes,
-
SysUtils,
-
Dialogs,
-
Interfaces,
-
Windows,
-
CustApp,
-
Messages,
-
Forms,
-
Controls,
-
Graphics;
-
type
-
{ TCreateMsgDlgApplication }
-
TCreateMsgDlgApplication = class(TCustomApplication)
-
public
-
procedure Run;
-
end;
-
{ TCreateMsgDlgApplication }
-
procedure TCreateMsgDlgApplication.Run;
-
var
-
TaskDialog: TTaskDialog;
-
Button: TTaskDialogBaseButtonItem;
-
begin
-
with TTaskDialog.Create(self) do
-
try
-
Title := ‘Confirm removal’;
-
Caption := ‘Confirm’;
-
Text := ‘Remove selected item?’;
-
CommonButtons := [];
-
with TTaskDialogButtonItem(Buttons.Add) do
-
begin
-
Caption := ‘Remove’;
-
ModalResult := mrYes;
-
end;
-
with TTaskDialogButtonItem(Buttons.Add) do
-
begin
-
Caption := ‘Keep’;
-
ModalResult := mrNo;
-
end;
-
MainIcon := tdiQuestion;
-
if Execute then
-
if ModalResult = mrYes then
-
ShowMessage(‘Item removed’);
-
finally
-
Free;
-
end;
-
end;
-
var
-
AppDlg: TCreateMsgDlgApplication;
-
begin
-
AppDlg := TCreateMsgDlgApplication.Create(nil);
-
AppDlg.Run;
-
AppDlg.Free;
-
end.
Do I need to include something else or am I totally going in the wrong direction ?
Project in attached.
« Last Edit: June 20, 2018, 10:42:35 pm by scons »
Logged
Windows 10-64bit Lazarus 2.0.12 + FPC 3.2.0
You need to initialize the widgetset before you can use that.
And yes, I know it is not Delphi compatible.
Bart
Logged
First test crashes with error:
Failed to create win32 control, error 1407
So it needs a windows something ??
Win32 error 1407 is ERROR_CANNOT_FIND_WND_CLASS, which means the task dialog’s window class hasn’t been registered.
Task Dialogs require ComCtrl32.dll v6, so make sure your EXE is adequately manifested to enable that (see Enabling Visual Styles on MSDN). And make sure your app is calling InitCommonControls/Ex() at runtime, either directly or via some FreePascal widget unit that handles that for you.
Logged
Thanks for your responses, got me thinking,
Menu : Project -> Project Options ->Application -> For Windows -> enabeling the checkbox «Use manifest resource (and enable themes)»
did the trick no error, runs fine.
Thanks !
Logged
Windows 10-64bit Lazarus 2.0.12 + FPC 3.2.0