Доброго дня!
1С:Предприятие 8.3 (8.3.9.2170), Управление производственным предприятием, редакция 1.3 (1.3.90.1). Формы обычные.
Есть кусок кода (хранится в справочнике):
Если Не ГМЗ_СогласованиеДокументов.ТребоватьПроверкуРасценкиЗаказногоЛимита(ПараметрыВыполненияКода.СсылкаДокумента) Тогда // Два ЕСЛИ, чтобы сократить длину строки Если (ПараметрыВыполненияКода.НовоеСостояниеДокумента = Перечисления.ГМЗ_СостоянияДокументов.Согласован) Тогда Если (ПараметрыВыполненияКода.НовоеСостояниеДокумента = Перечисления.ГМЗ_СостоянияДокументов.Утвержден) Тогда прм_Запрос = Новый Запрос; прм_Запрос.Текст = "ВЫБРАТЬ РАЗЛИЧНЫЕ | ГМЗ_УстановкаЦенМатериаловЛимитов.Ссылка |ИЗ | Документ.ГМЗ_УстановкаЦенМатериаловЛимитов КАК ГМЗ_УстановкаЦенМатериаловЛимитов |ГДЕ | ГМЗ_УстановкаЦенМатериаловЛимитов.Проведен = ИСТИНА | И ГМЗ_УстановкаЦенМатериаловЛимитов.ДокументЛимитов = &ДокументЛимитов"; прм_Запрос.УстановитьПараметр("ДокументЛимитов", ПараметрыВыполненияКода.СсылкаДокумента); прм_РезультатЗапроса = прм_Запрос.Выполнить(); прм_Выб = прм_РезультатЗапроса.Выбрать(); прм_НовоеСостояние = Перечисления.ГМЗ_СостоянияДокументов.Утвержден; прм_Комментарий = "Утвержден при утверждении документа лимита"; прм_РезОперации = ""; Пока прм_Выб.Следующий() Цикл прм_СтрК = Новый Структура("Состояние, Комментарий", прм_НовоеСостояние, прм_Комментарий); прм_Рез = ГМЗ_СогласованиеДокументов.УстановитьНовоеСостояниеДокумента(прм_Выб.Ссылка, прм_СтрК); прм_РезОперации=?(прм_РезОперации = "","",прм_РезОперации +Символы.ПС+"Утверждение "+СокрЛП(прм_Выб.Ссылка)+":"+?(прм_Рез = "", "ОК", "ОШИБКА!!! " + прм_Рез)); КонецЦикла; ПараметрыВыполненияКода.СтатусОбработкиДокумента = прм_РезОперации; КонецЕсли; КонецЕсли; КонецЕсли;
В модуле формы обработки вызываю
ПараметрыВыполненияКода = Новый Структура("СсылкаДокумента, СсылкаПроверяемогоЭтапа, НовоеСостояниеДокумента, СтатусОбработкиДокумента"); ПараметрыВыполненияКода.СсылкаДокумента = СтрокаТабличнойЧасти.Ссылка; ПараметрыВыполненияКода.СсылкаПроверяемогоЭтапа = НовыйЭтап; ПараметрыВыполненияКода.НовоеСостояниеДокумента = НовоеСостояниеТекущегоДокумента; ПараметрыВыполненияКода.СтатусОбработкиДокумента = ""; Выполнить(КодПостОбработки);
…
Вылезает вот такая ошибка: Ошибка компиляции при вычислении выражения или выполнении фрагмента кода: {(37,96)}: Ожидается символ ‘)’
Несмотря на это, при вставке кода напрямую в модуль формы (вместо Выполнить(КодПостОбработки)) все работает!
Я пытался уменьшить длину строк текста, все тщетно. Может, есть какие-то ограничения платформы?
Спасибо.
Здравствуйте, коллеги! Сегодня поговорим о проблеме неопределенных переменных в 1С. Рядовой пользователь с данной ошибкой сталкиваться не должен, но если уж и произошло подобное при работе в типовой конфигурации 1С, которая никак не модифицировалась, возможно, у нас наклевывается проблема самого релиза, которая иссякнет при обновлении. В таком случае стоит связаться со специалистом, чтобы найти выход из ситуации.
Если же Вы сами занимаетесь разработкой и столкнулись с ошибкой, «Переменная не определена в 1С», то следует обратится к конфигуратору, найти, что за переменная и в какой именно момент не определена. Есть несколько вариантов решения, но нужно подбирать их с умом, ибо вполне возможно, что после неправильного исправления в одном месте, Вы получите кучу ошибок в других местах.
1. Проверка на определения 1С 8.3
Можно прописать перед ошибкой следующий код:
Если Не НашаПеременная = Неопределено Тогда
Соответственно, закрыв «Если» после, но тут как уже писалось нужно действовать аккуратно, возможно данная конструкция напрочь сломает весь последующий код. Гораздо лучше найти, где объявляется переменная и устранить ошибку.
2. Поиск объявления переменной 1С 8.3
Если переменная объявляется в той же функции, то это просто замечательно! Нужно только понять, почему же код с объявлением оставил переменную неопределенной, и исправить это.
Вполне возможен вариант, что ее просто забыли включить в передаваемые параметры функции или она не доступна в данном виде клиента. Такое случается, когда, например, обращаются из тонкого клиента к метаданным. В этом случае стоит переписать функцию или, возможно, объявить новую, но уже на сервере, которая вернет необходимые тонкому клиенту данные.
3. Обычная опечатка в программе 1С 8.3 Предприятие
Чтобы быстро в программе 1С 8.3 Предприятие проверить опечатка ли спровоцировала ошибку, просто скопируем переменную из объявления и вставим ее имя в то место, где случается ошибка. Можно сделать следующим образом, чтобы избежать таких ошибок в будущем:
Теперь, когда курсор останавливается на идентификаторе, все другие его упоминания будут выделены, как на следующем изображении:
Переменная не определена в 1С 8.3
Ошибка Переменная не определена в 1С 8.3 указывает на то, что программа не может получить нужную информацию в исполняемом программном коде. Это может быть связано с обновлением или доработкой программы. Если стандартный набор действий при исправлении ошибок не помог:
Придется разбираться с местом возникновения ошибки в 1С самостоятельно.
БухЭксперт8 подготовил 3 примера получения и исправления ошибки:
Ошибка в доработанном программном коде
В сообщении об ошибке указано место возникновения ошибки — строка 919 в модуле формы. Для исправления ошибки необходимо выполнить следующие действия:
Синтаксис Справочники. Склады. ОсновнойСклад используется только для предопределенного склада с именем ОсновнойСклад :
Ошибка вывода печатной формы
Для вывода в печатную форму накладной данных об ответственном менеджере, оформившем документ поступления, программист внес изменения в макет ПФ_MXL_Накладная и программный код.
В макет документа добавлена область Подвал :
В программном коде дописан вывод данных области Подвал :
После доработки программы при попытке вывода накладной на печать 1С выдает ошибку:
После исправления программного кода накладная сформируется без ошибки.
Ошибка исполнения кода на Клиенте
С переходом на управляемые формы в Бухгалтерия 3.0 работы программистам прибавилось.
Язык программирования стал сложнее. Часть команд теперь могут выполняться только на стороне клиента — это, условно говоря, компьютер пользователя, который посылает запросы на исполнение операций серверу. Сервер обрабатывает все поступившие запросы и отсылает обратно клиенту результат обработки данных.
Разделение команд в программном коде не зависит от того, используете ли вы файловую или клиент-серверную 1С. Разграничение должно четко исполняться, иначе будут возникать ошибки, одну из которых БухЭксперт8 разберет на примере.
Теперь сохранение изменений пройдет без ошибки.
Усложнение языка программирования 1С требует от разработчика более глубокого подхода к вносимым изменениям в программу. Недостаточно просто знать синтаксис команды, важно еще правильно задать область исполнения команды в режиме управляемых форм.
См. также:
Помогла статья?
Получите еще секретный бонус и полный доступ к справочной системе БухЭксперт8 на 14 дней бесплатно
Карточка публикации
Добавить комментарий Отменить ответ
Для отправки комментария вам необходимо авторизоваться.
Вы можете задать еще вопросов
Доступ к форме «Задать вопрос» возможен только при оформлении полной подписки на БухЭксперт8
Нажимая кнопку «Задать вопрос», я соглашаюсь с
Регламентом БухЭксперт8.ру >>
Переменная не определена в 1С 8.3
В программе 1С для промежуточного хранения информации любого типа используются переменные. В процессе исполнения программного кода, если переменной не присвоено никакого значения, пользователю выдается ошибка в 1С «Переменная не определена». Рассмотрим, как ее исправить.
Использование переменных в 1С
Переменные указываются в структуре кода с использованием знака равенства (=) или перечисляются после ключевого слова Перем в одноименном разделе модулей, кроме общего и модуля сеанса.
Тип переменной заранее не задается, а определяется после присвоения какого-либо значения. В памяти они не хранятся, а создаются в момент исполнения кода и стираются с завершением операций. Различают 3 вида переменных:
Глобальные переменные
Объявляются в верхней части модулей до процедур/функций в разделе объявления переменных. Имена перечисляются после ключевого слова Перем через запятую. Присвоение значений происходит в процессе выполнения кода, изначально имеет тип [Неопределено].
Глобальные переменные можно использовать в модулях:
В модулях формы и команды для каждой процедуры/функции определяется место исполнения: на сервере (&НаСервере, &НаСервереБезКонтекста) или на клиенте (&НаКлиенте), при этом режим работы программы (серверный или файловый) не имеет значения. Объявленные глобальные переменные в этих модулях во время выполнения кода:
Локальные переменные
Определяются в процедуре/функции при помощи равенства какому-либо значению, доступны только в пределах своей процедуры/функции, не могут выйти за рамки кода и стираются после ее завершения.
Экспортные переменные
В разделе переменных после имени имеют ключевое слово Экспорт, которое позволяет экспортировать их в любое место программы через обращение к модулю-родителю.
Ошибка «Переменная не определена» в 1С 8.3
Когда программа 1С не может найти переменную, пользователю выдается сообщение «Переменная не определена ([Имя_переменной])».
Сбой может возникнуть после обновления или доработки конфигурации. Первичные действия по устранению ошибки будут такими же, как при появлении других предупреждающих сообщений, например, «Поле объекта не обнаружено» или «Метод объекта не обнаружен»:
Если ни один из вышеуказанных способов не дал результата, то для решения проблемы с ошибкой «Переменная не определена» потребуется разобрать в программном коде и при необходимости внести правки.
Кроме текста ошибки в окне указано место ее возникновения:
В конфигураторе откроется модуль, в котором не удалось определить переменную, а курсор автоматически переместится на ее имя.
Способы устранения ошибки
Если переменная не определена в процедуре/функции, исполняемой на стороне клиента (&НаКлиенте):
Когда ошибку «Переменная не определена» 1С 8.3 выдает при выполнении серверной процедуры/функции (&НаСервере, &НаСервереБезКонтекста):
При внесении самостоятельных изменений в программный код не удаляйте строки, а превращайте в комментарии, добавляя двойной правый слеш перед текстом. Это позволит восстановить первоначальный вариант кода. Перед корректированием части строчки кода также копируйте ее первоначальный вид в комментарий.
Для исправления ошибки «Переменная не определена» в управляемых формах мало понимать синтаксические конструкции кода: потребуются знания о месте их исполнения — сервер или клиент. Пользователь может выяснить причину сбоя самостоятельно, но для решения проблемы лучше обратиться к программисту.
Источники:
Https://www. koderline. ru/expert/instruktsii/article-peremennaya-ne-opredelena-v-1s/
Https://buhexpert8.ru/obuchenie-1s/oshibki-v-1s/peremennaya-ne-opredelena-v-1s-8-3.html
Https://profbuh8.ru/2020/12/peremennaya-ne-opredelena-v-1s-8-3/
In one of my prof slides on ploymorphism, I see this piece of code with a couple of comments:
discountVariable = //will produce
(DiscountSale)saleVariable;//run-time error
discountVariable = saleVariable //will produce
//compiler error
As you can see, it says in the first casting statement that it’ll produce run-time error and in the other one it says it’ll produce compiler error.
What makes these errors? and how they differ from each other?
The Unfun Cat
28.9k29 gold badges110 silver badges150 bronze badges
asked Feb 27, 2012 at 20:31
3
A run time error will only occur when the code is actually running.
These are the most difficult — and lead to program crashes and bugs in your code which can be hard to track down.
An example might be trying to convert a string: «hello» into an integer:
string helloWorld = "hello";
int willThrowRuntimeError = Convert.ToInt32(helloWorld);
The compiler may not see this as a problem but when run an error will be thrown.
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
An example of a compiler error would be:
int = "this is not an int";
user
5,2826 gold badges19 silver badges35 bronze badges
answered Feb 27, 2012 at 20:38
DIXONJWDDDIXONJWDD
1,25610 silver badges20 bronze badges
1
A runtime error happens during the running of the program. A compiler error happens when you try to compile the code.
If you are unable to compile your code, that is a compiler error.
If you compile and run your code, but then it fails during execution, that is runtime.
answered Feb 27, 2012 at 20:33
James MontagneJames Montagne
76.8k14 gold badges108 silver badges129 bronze badges
2
Compile time errors refers to syntax and semantics. For example, if you do operations that involves different types. Ex: adding a string with an int, or dividing a string by a real. (read the last paragraph thou!!!)
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution.
This is a very broad explanation. There are many smart compilers, and, also, is possible to do internal casting among different types that leads to operations that make sense. It it possible to pre-compile code and see some run time errors even if the code is not executed.
Refer to this link too: Runtime vs Compile time
answered Feb 27, 2012 at 20:37
Compile time errors are errors of syntax and semantics.
Run time errors are errors of logic primarily. Due to something the programmer has overlooked, the program crashes e.g. division by 0, accessing a variable without initializing it first etc.
answered Jun 8, 2015 at 7:03
HadiHadi
5008 silver badges20 bronze badges
Compile Time error means that the Compiler knows that discountVariable = saleVariable
must be end with a semi colon as belowdiscountVariable = saleVariable;
so it will throw an error when you compile the code.
Run Time error means that the error will occur at run time, because even though you are casting saleVariable into discountVariable, the cast cannot take because they differ in type.
answered Feb 27, 2012 at 20:33
CodeBlueCodeBlue
14.5k32 gold badges94 silver badges131 bronze badges
think you’ve already got the general desc of what’s the difference. Specifically in the code you have shown in the OP,
- In second statement, compiler compares the types on LHS and RHS and finds no implicit cast possible so it gives the error.
- first statement is seen by compiler as the same, but here programmer explicitly casts the type, which is as good as telling compiler that I know what I’m doing and of course the compiler trusts you and gives you no errors.
answered Feb 27, 2012 at 20:50
KashyapKashyap
14.5k12 gold badges63 silver badges100 bronze badges
1
Its because the compiler doesn’t know the object type of «saleVariable» until that value has actually been set when the program is running.
Your are forcing whatever is in salesVariable into the type DiscountSale this is considered unsafe and cannot be evaluated until runtime.
answered Feb 27, 2012 at 20:33
bigamilbigamil
6574 silver badges12 bronze badges
2
Compilation/Compile time/Syntax/Semantic errors: Compilation or compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler. They wont let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors.
Example: Missing a semicolon in C or mistyping int
as Int
.
Runtime errors: Runtime errors are the errors that are generated when the program is in running state. These types of errors will cause your program to behave unexpectedly or may even kill your program. They are often referred as Exceptions.
Example: Suppose you are reading a file that doesn’t exist, will result in a runtime error.
Read more about all programming errors here
answered May 25, 2015 at 5:37
If you’d use Google, you’d get this:
Compile time error is any type of error that prevent a java program compile like a syntax error, a class not found, a bad file name for the defined class, a possible loss of precision when you are mixing different java data types and so on.
A runtime error means an error which happens, while the program is running. To deal with this kind of errors java define Exceptions. Exceptions are objects represents an abnormal condition in the flow of the program. It can be either checked or unchecked.
http://wiki.answers.com/Q/Difference_between_run_time_error_and_compile_time_error_in_java
answered Feb 27, 2012 at 20:32
2
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
Ex :- MethodOverloading
class OverloadingTest {
void sum(int a, long b) {
System.out.println("a method invoked");
}
void sum(long a, int b) {
System.out.println("b method invoked");
}
public static void main(String args[]) {
OverloadingTest obj = new OverloadingTest();
obj.sum(200, 200);// now ambiguity
}
}
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution
answered Apr 21, 2015 at 8:48
Nikhil KumarNikhil Kumar
2,5183 gold badges19 silver badges24 bronze badges
In one of my prof slides on ploymorphism, I see this piece of code with a couple of comments:
discountVariable = //will produce
(DiscountSale)saleVariable;//run-time error
discountVariable = saleVariable //will produce
//compiler error
As you can see, it says in the first casting statement that it’ll produce run-time error and in the other one it says it’ll produce compiler error.
What makes these errors? and how they differ from each other?
The Unfun Cat
28.9k29 gold badges110 silver badges150 bronze badges
asked Feb 27, 2012 at 20:31
3
A run time error will only occur when the code is actually running.
These are the most difficult — and lead to program crashes and bugs in your code which can be hard to track down.
An example might be trying to convert a string: «hello» into an integer:
string helloWorld = "hello";
int willThrowRuntimeError = Convert.ToInt32(helloWorld);
The compiler may not see this as a problem but when run an error will be thrown.
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
An example of a compiler error would be:
int = "this is not an int";
user
5,2826 gold badges19 silver badges35 bronze badges
answered Feb 27, 2012 at 20:38
DIXONJWDDDIXONJWDD
1,25610 silver badges20 bronze badges
1
A runtime error happens during the running of the program. A compiler error happens when you try to compile the code.
If you are unable to compile your code, that is a compiler error.
If you compile and run your code, but then it fails during execution, that is runtime.
answered Feb 27, 2012 at 20:33
James MontagneJames Montagne
76.8k14 gold badges108 silver badges129 bronze badges
2
Compile time errors refers to syntax and semantics. For example, if you do operations that involves different types. Ex: adding a string with an int, or dividing a string by a real. (read the last paragraph thou!!!)
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution.
This is a very broad explanation. There are many smart compilers, and, also, is possible to do internal casting among different types that leads to operations that make sense. It it possible to pre-compile code and see some run time errors even if the code is not executed.
Refer to this link too: Runtime vs Compile time
answered Feb 27, 2012 at 20:37
Compile time errors are errors of syntax and semantics.
Run time errors are errors of logic primarily. Due to something the programmer has overlooked, the program crashes e.g. division by 0, accessing a variable without initializing it first etc.
answered Jun 8, 2015 at 7:03
HadiHadi
5008 silver badges20 bronze badges
Compile Time error means that the Compiler knows that discountVariable = saleVariable
must be end with a semi colon as belowdiscountVariable = saleVariable;
so it will throw an error when you compile the code.
Run Time error means that the error will occur at run time, because even though you are casting saleVariable into discountVariable, the cast cannot take because they differ in type.
answered Feb 27, 2012 at 20:33
CodeBlueCodeBlue
14.5k32 gold badges94 silver badges131 bronze badges
think you’ve already got the general desc of what’s the difference. Specifically in the code you have shown in the OP,
- In second statement, compiler compares the types on LHS and RHS and finds no implicit cast possible so it gives the error.
- first statement is seen by compiler as the same, but here programmer explicitly casts the type, which is as good as telling compiler that I know what I’m doing and of course the compiler trusts you and gives you no errors.
answered Feb 27, 2012 at 20:50
KashyapKashyap
14.5k12 gold badges63 silver badges100 bronze badges
1
Its because the compiler doesn’t know the object type of «saleVariable» until that value has actually been set when the program is running.
Your are forcing whatever is in salesVariable into the type DiscountSale this is considered unsafe and cannot be evaluated until runtime.
answered Feb 27, 2012 at 20:33
bigamilbigamil
6574 silver badges12 bronze badges
2
Compilation/Compile time/Syntax/Semantic errors: Compilation or compile time errors are error occurred due to typing mistake, if we do not follow the proper syntax and semantics of any programming language then compile time errors are thrown by the compiler. They wont let your program to execute a single line until you remove all the syntax errors or until you debug the compile time errors.
Example: Missing a semicolon in C or mistyping int
as Int
.
Runtime errors: Runtime errors are the errors that are generated when the program is in running state. These types of errors will cause your program to behave unexpectedly or may even kill your program. They are often referred as Exceptions.
Example: Suppose you are reading a file that doesn’t exist, will result in a runtime error.
Read more about all programming errors here
answered May 25, 2015 at 5:37
If you’d use Google, you’d get this:
Compile time error is any type of error that prevent a java program compile like a syntax error, a class not found, a bad file name for the defined class, a possible loss of precision when you are mixing different java data types and so on.
A runtime error means an error which happens, while the program is running. To deal with this kind of errors java define Exceptions. Exceptions are objects represents an abnormal condition in the flow of the program. It can be either checked or unchecked.
http://wiki.answers.com/Q/Difference_between_run_time_error_and_compile_time_error_in_java
answered Feb 27, 2012 at 20:32
2
Compiler errors are due to inaccuracies in code, where the compiler throws an error to alert you to something which will not compile, and therefore cannot be run.
Ex :- MethodOverloading
class OverloadingTest {
void sum(int a, long b) {
System.out.println("a method invoked");
}
void sum(long a, int b) {
System.out.println("b method invoked");
}
public static void main(String args[]) {
OverloadingTest obj = new OverloadingTest();
obj.sum(200, 200);// now ambiguity
}
}
Run Time errors are those that are detected when the program execute. For example, division by zero. The compiler can not know if the operation x/a-b will leads to division by zero until the execution
answered Apr 21, 2015 at 8:48
Nikhil KumarNikhil Kumar
2,5183 gold badges19 silver badges24 bronze badges
|