Floating point overflow как исправить

Как исправить ошибку floating point overflow? Delphi Решение и ответ на вопрос 2164381

0 / 0 / 0

Регистрация: 21.04.2015

Сообщений: 20

1

24.12.2017, 18:30. Показов 3319. Ответов 4


Здраствуйте помогите мне с программой при считывании у меня выходит ошибка «floating point overflow».
Вот программа

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

24.12.2017, 18:30

Ответы с готовыми решениями:

Floating point overflow
Программа компилится, но при запуске и нажатии баттона (код ниже) возникает фат. ошибка и…

floating point overflow
Здравствуйте. Помогите, пожалуйста, разобраться с данной проблемой, как её решить?
вылетает с…

Floating point overflow
Здравствуйте! Задание состоит в том, чтобы вычислить значение суммы следующего ряда с требуемой…

Floating point overflow
Очень долго возился с этим заданием.Еле-еле понял как делать.Теперь выдает ошибку "Floating point…

4

1073 / 986 / 340

Регистрация: 07.08.2012

Сообщений: 2,790

24.12.2017, 19:19

2

Дельфи не признает разделитель «запятая» между целой и дробной частями числа.
Разделителем должен быть символ «точка».
Проверка показала, что после замены запятой на точку вычисления происходят без ошибок

Миниатюры

Как исправить ошибку floating point overflow?
 



0



Модератор

1436 / 1012 / 228

Регистрация: 31.05.2013

Сообщений: 6,645

Записей в блоге: 6

24.12.2017, 19:28

3

Цитата
Сообщение от Скандербег
Посмотреть сообщение

Дельфи не признает разделитель «запятая» между целой и дробной частями числа.

Признаёт. Просто Delimiter по умолчанию установлен на «.» . Так что либо установить Delimiter := ‘,’ либо заменить в поле ввода запятую на точку.



1



Скандербег

1073 / 986 / 340

Регистрация: 07.08.2012

Сообщений: 2,790

24.12.2017, 20:00

4

Да, действительно, можно изменить умолчальный разделитель, но попробуйте это популярно растолковать новичкам.
Ведь тогда им придется в каждой своей программе менять.


Все же, в продолжении, приведу пример как изменить разделитель дробной части числа в конкретной программе.
В любом модуле проекта в секции инициализации пишется следующее:

Delphi
1
2
3
initialization
  FormatSettings.DecimalSeparator := ','; 
end.



0



пофигист широкого профиля

4602 / 3062 / 850

Регистрация: 15.07.2013

Сообщений: 17,660

25.12.2017, 02:33

5

Скандербег, Matan!,
Господа-камрады А при чём тут разделитель целой и дробной части? ТС ведь заявил ошибку с «floating point overflow».
P.S.
Возможно у этой темы была предистория, которую я не знаю.
P.P.S.
Но насчет разделителя вы оба даёте неверные советы. Наши люди употребляют и точку и запятую. В большинстве своём даже не думая. Так что если нужно писать ПО с элементами ввода чисел — самое лучшее решение (трудоёмкое для программиста — это да) — контролировать ввод и заменять символы «точка» и «запятая» на DecimalSeparator.



0



Умея
пользоваться массивами, условными
операторами и операторами цикла, вы
можете писать довольно серьезные
программы. При выполнении этих программ
неизбежно будут возникать критические
ошибки, приводящие к аварийному завершению
программы. Такие ошибки по английски
называются Run-time errors — ошибки времени
выполнения. Рассмотрим пока только
наиболее часто встречающиеся арифметические
ошибки:

Division
by zero — код ошибки 200;

Arithmetic
overflow — код ошибки 215;

Range
check error — код ошибки 201;

Floating
point overflow — код ошибки 205;

Invalid
floating point operation — код ошибки 207.

Ошибка
Division
by zero

— деление на ноль — возникает при выполнении
операций DIV,
MOD

и /,
когда делитель равен нулю.

Ошибка
Arithmetic overflow

— целочисленное переполнение — возникает
при выполнении арифметической операции
над целыми числами, когда результат
операции выходит за границы соответствующего
типа. Такая ошибка произойдет, например,
при выполнении программы

VAR
a,b : Word; c : Integer; BEGIN a:=100; b:=200; c:=a-b; END.

Ошибка
произошла, когда вычислилось значение
выражения a-b,
равное -100.
Мы знаем, что при выполнении операции
над операндами типа Word
результат будет иметь тип Word,
а -100 не является допустимым значением
этого типа. То обстоятельство, что это
значение мы собирались присвоить
переменной типа Integer,
не
имеет значения, т.к. ошибка произошла
до
присваивания. Интересно, что, если
описать a
и
b

как
Byte
,
то ошибки не будет (см. таблицу 2 в главе
5).

Ошибка
Range
check error

— ошибка проверки диапазона — происходит
в двух случаях. Во-первых, при попытке
присвоить целочисленной переменной
недопустимое значение, и, во-вторых, при
использовании недопустимого индексного
выражения для элемента любого массива.
Проиллюстрируем оба эти случая на
простых примерах.

VAR
a,b,c : Word; BEGIN a:=$FFFF; b:=1; c:=a+b; END.

Мы
попытались присвоить переменной типа
Word
значение 65536, которое не является
допустимым для этого типа.

VAR
x : ARRAY[2..8] OF Real; i : Byte;

BEGIN
FOR i:=8 DOWNTO 1 DO x[i]:=Sqrt(i); END.

Ошибка
произошла при обращении к первому
элементу массива, который не существует.
Фактически этот второй случай полностью
аналогичен первому — мы попытались
«присвоить» индексу массива, тип
которого-2..8, значение 1.

Ошибка
Floating
point overflow

— вещественное переполнение — возникает
при выполнении операции над вещественными
числами, когда результат операции
слишком велик, или при попытке присвоить
вещественной переменной слишком большое
значение. Когда речь идет о вещественных
числах, термин «слишком большое»
следует понимать как большое по абсолютной
величине — знак числа не имеет значения.
Приведем пример программы, содержащей
такую ошибку.

VAR
r : Real; BEGIN r:=-1E20; r:=Sqr(r); END.

При
возведении в квадрат величины r
мы получим слишком большое для типа
Real
число
1E40.

Ошибка
Invalid
floating point operation

возникает в трех случаях:

1)
при вычислении корня из отрицательного
числа;

2)
при вычислении логарифма неположительного
числа;

3)
при вычислении функций Trunc и Round от
слишком большого (по абсолютной величине)
вещественного числа. Эта ошибка довольно
очевидна, и мы не станем ее иллюстрировать.

Как
же должен поступать программист, когда
при выполнении его программы возникают
ошибки? Прежде всего нужно локализовать
ошибку, то есть найти оператор, в котором
она произошла. В этом вам может помочь
среда Turbo Pascal, если в ней правильно
установлены опции
компилятора
.
Опции компилятора позволяют изменять
режим компиляции и задаются в подменю
Compiler
меню Options
среды Turbo Pascal. Пока нас будут интересовать
лишь пять опций: Range
checking
,
Stack
cheking
,
I/O
checking
,
Overflow
checking
,
Debug
information.
Если они включены, то настройка среды
благоприятна для отладки вашей программы.
Если они выключены, то их обязательно
следует включить, а еще лучше задать их
непосредственно в тексте своей программы.
Опции записываются в программе в виде:

{$
буква
+
/
}

Каждой
опции соответствует своя буква (эти
буквы выделены в подменю Compiler
цветом), символ «+» означает включить,
а символ «-» — выключить. В программе
можно задать одну опцию, например, {$R+}
или несколько опций — {$R+,I-,S+}
. Некоторые опции можно записывать
только в самом начале программы, другие
могут размещаться в любом ее месте.

Опция
Range
checking

(R) отвечает за контроль ошибок Range
check error
,
Overflow
checking

(C) — за контроль ошибок Ariphmetic
overflow
,
I/O
cheking

(I) — за контроль ошибок ввода-вывода.
Смысл опции Stack
cheking

(S) будет объяснен несколько позже, а
опция Debug
information

(D) включает в код программы отладочную
информацию, что позволяет среде Turbo
Pascal при аварийном завершении программы
показать курсором оператор, в котором
произошла ошибка. Позаботьтесь, чтобы
при отладке программы перед первым ее
оператором была строка {$R+,C+,I+,S+,D+}
— это поможет вам найти и устранить все
ошибки. Некоторые неопытные программисты
выключают эти опции, тогда программа
не прерывается при некоторых ошибках,
а продолжает выполняться, на этом
основании делается вывод, что программа
верна. Это самообман — программа
выполняется, но выполняется неправильно
и никак не сообщает об ошибках.

Соседние файлы в папке Учебники

  • #
  • #

Maybe you need to debug an implementation of an algorithm where you may have made a coding mistake and want to trace the floating point computations being carried out. Maybe you need a hook to inspect all values being operated on, looking for values that appear to be out of the range you expect. In C++ you can define your own floating point class and use operator overloading to write your calculations in a natural way, while retaining the ability to inspect all calculations.

For example, here’s a program that defines an FP class, and prints out all additions and multiplications.

#include <iostream>
struct FP {
    double value;
    FP( double value ) : value(value) {}
};
std::ostream & operator<< ( std::ostream &o, const FP &x ) { o << x.value; return o; }
FP operator+( const FP & lhs, const FP & rhs ) {
    FP sum( lhs.value + rhs.value );
    std::cout << "lhs=" << lhs.value << " rhs=" << rhs.value << " sum=" << sum << std::endl;
    return sum;
}
FP operator*( const FP & lhs, const FP & rhs ) {
    FP product( lhs.value * rhs.value );
    std::cout << "lhs=" << lhs.value << " rhs=" << rhs.value << " product=" << product << std::endl;
    return product;
}

int main() {
    FP x = 2.0;
    FP y = 3.0;
    std::cout << "answer=" << x + 2 * y << std::endl;
    return 0;
}

Which prints

lhs=2 rhs=3 product=6
lhs=2 rhs=6 sum=8
answer=8

Update: I’ve enhanced the program (on x86) to show the floating point status flags after each floating point operation (only implemented addition and multiplication, others could be easily added).

#include <iostream>

struct MXCSR {
    unsigned value;
    enum Flags {
        IE  = 0, // Invalid Operation Flag
        DE  = 1, // Denormal Flag
        ZE  = 2, // Divide By Zero Flag
        OE  = 3, // Overflow Flag
        UE  = 4, // Underflow Flag
        PE  = 5, // Precision Flag
    };
};
std::ostream & operator<< ( std::ostream &o, const MXCSR &x ) {
    if (x.value & (1<<MXCSR::IE)) o << " Invalid";
    if (x.value & (1<<MXCSR::DE)) o << " Denormal";
    if (x.value & (1<<MXCSR::ZE)) o << " Divide-by-Zero";
    if (x.value & (1<<MXCSR::OE)) o << " Overflow";
    if (x.value & (1<<MXCSR::UE)) o << " Underflow";
    if (x.value & (1<<MXCSR::PE)) o << " Precision";
    return o;
}

struct FP {
    double value;
    FP( double value ) : value(value) {}
};
std::ostream & operator<< ( std::ostream &o, const FP &x ) { o << x.value; return o; }
FP operator+( const FP & lhs, const FP & rhs ) {
    FP sum( lhs.value );
    MXCSR mxcsr, new_mxcsr;
    asm ( "movsd %0, %%xmm0 nt"
          "addsd %3, %%xmm0 nt"
          "movsd %%xmm0, %0 nt"
          "stmxcsr %1 nt"
          "stmxcsr %2 nt"
          "andl  $0xffffffc0,%2 nt"
          "ldmxcsr %2 nt"
          : "=m" (sum.value), "=m" (mxcsr.value), "=m" (new_mxcsr.value)
          : "m" (rhs.value)
          : "xmm0", "cc" );

    std::cout << "lhs=" << lhs.value
              << " rhs=" << rhs.value
              << " sum=" << sum
              << mxcsr
              << std::endl;
    return sum;
}
FP operator*( const FP & lhs, const FP & rhs ) {
    FP product( lhs.value );
    MXCSR mxcsr, new_mxcsr;
    asm ( "movsd %0, %%xmm0 nt"
          "mulsd %3, %%xmm0 nt"
          "movsd %%xmm0, %0 nt"
          "stmxcsr %1 nt"
          "stmxcsr %2 nt"
          "andl  $0xffffffc0,%2 nt"
          "ldmxcsr %2 nt"
          : "=m" (product.value), "=m" (mxcsr.value), "=m" (new_mxcsr.value)
          : "m" (rhs.value)
          : "xmm0", "cc" );

    std::cout << "lhs=" << lhs.value
              << " rhs=" << rhs.value
              << " product=" << product
              << mxcsr
              << std::endl;
    return product;
}

int main() {
    FP x = 2.0;
    FP y = 3.9;
    std::cout << "answer=" << x + 2.1 * y << std::endl;
    std::cout << "answer=" << x + 2 * x << std::endl;
    FP z = 1;
    for( int i=0; i<310; ++i) {
        std::cout << "i=" << i << " z=" << z << std::endl;
        z = 10 * z;
    }

    return 0;
}

The last loop multiplies a number by 10 enough times to show overflow happen. You’ll notice precision errors happen as well. It ends with the value being infinity once it overflows.

Here’s the tail of the output

lhs=10 rhs=1e+305 product=1e+306 Precision
i=306 z=1e+306
lhs=10 rhs=1e+306 product=1e+307
i=307 z=1e+307
lhs=10 rhs=1e+307 product=1e+308 Precision
i=308 z=1e+308
lhs=10 rhs=1e+308 product=inf Overflow Precision
i=309 z=inf
lhs=10 rhs=inf product=inf



Сообщ.
#1

,
08.12.09, 15:49

    Добрый день. Такая вот проблема при написании программы в Borland Pascal 7.0.
    Необходимо решить дифференциальное уравнение и затем вывести решение в виде графика. Однако При запуске программы появляется такая ошибка: «Floating point overflow». Я догадываюсь, что это что-то про плавающую запятую и что, видимо, там перевес или типо этого но как устранить это — я не знаю. Ниже привожу выдержку из программы:

    begin
    begin
    f1:=(3333333-(33333333*Y[2]*0.13))*0.13;
    PY[1]:=Y[2];
    PY[2]:=(((f1)-300000*0.13)/J);
    end;
    if f1>300000*0.13 then f1:=300000*0.13;

    end;

    Причем ругается на f1. Пробывал уменьшать само f1 умноженнием не на 0.13, а на 0.013. Все хорошо. Только вот мне нужно именно такое значение функции при таком большом значении аргумента :)

    И еще такой вопрос в тему: есть ли возможность в паскале копировать графики? мне необходимо как-то их вытянуть в документ Word’a.

    Подскажите, каковы пути решения проблемы.

    Guru

    volvo877



    Сообщ.
    #2

    ,
    08.12.09, 16:22

      Moderator

      *******

      Рейтинг (т): 878

      Приводи код полностью. Вместе со всеми исходными данными, чтобы иметь возможность повторить ошибку.


      nigvil



      Сообщ.
      #3

      ,
      08.12.09, 16:31

        привожу.

        ExpandedWrap disabled

          Program TForm1;

          uses Graph;

          var M1,V1,b,V0:real;

              i1,DR,MO,d:integer;

              h,t,M,a,J,z : real;

              TK,TN,NS,t2,y4,t5,f1 : real;

              N,JJ,i,NSS,t4,y3,t6,y5,y6,y7,Gr,x1,u,f11 : longint;

              Ns1,t1,y1,t3,y2:string;

              out1:text;

              y,py,k1,k2,k3,k4,yy : array[0..7] of real;

              UM,L,F2,V2,MS,Ms1:real;

              dL,C,Fupr,TT,Fk,Ur,Up,Ud,U2,Uust,ust,Id,Iu,eps:real;

          Procedure DERY(VAR T1:real);

          begin

              begin

                begin

                    f1:=(3333333-(33333333*Y[2]*0.13))*0.13;

                    PY[1]:=Y[2];

                    PY[2]:=(((f1)-300000*0.13)/J);

                end;

               if f1>300000*0.13 then f1:=300000*0.13;

              end;

              {M1:=M*sqr(arctan(a*6)*(1-Y[2]/V0)/(1-b*Y[2]/V0))}

          end;

          BEGIN

          assign(out1,’d:out1.txt’);

          rewrite(out1);

              Dr:=detect;

              InitGraph(Dr,Mo,»);

              setGraphMode(2);

              setBKcolor(15);

               Write(‘Graph/Table-0/1: ‘);

              Readln(Gr);

              ust:=5;

              Iu:=8;

              d:=0;

              Fupr:=0;

              UM:=80;

              L:=5;

              V0:=0.077;

              V1:=0;

              MS:=1000;

              M:=33600;

              J:=1000;

              a:=0.5;

              Y[1]:=0;

              y[2]:=0;

              b:=0.93;

              y5:=0;

              t6:=3;

              TN:=0;

              TK:=2;

              h:=0.01;

              N:=2;

              T:=TN;

              TT:=0;

              NS:=1+(TK-TN)/h;

              NSS:=round(NS);

              FOR JJ:=1 TO NSS do

              begin

                DERY(t);

               {t4:=round(t*30);

                y5:=round(-Y[2]*1); {  Y[2]  }

                y5:=y5+300;

               { f11:=round(f1); }

                If Gr=0 then

                begin

                 {  PutPixel(f11,y5,6); }

                 {  writeln(out1,f1,’ ‘,Y[2]*0.13); }

                 PutPixel(t4,y5,6);

                 writeln(out1,f1/0.13,’ ‘,Y[2]*0.13);

                end else

                FOR i:=1 TO N do

                begin

                  K1[i]:=PY[i]*h;

                  YY[i]:=Y[i]+K1[i]/2;

                end;

                  T:=T+h/2;

                  DERY(T);

                  T:=T-h/2;

                  FOR i:=1 TO N do

                  begin

                    K2[i]:= PY[i]*h;

                    YY[i]:= Y[i]+K2[i]/2;

                  end;

                    T:=T+h/2;

                    DERY(T);

                    T:=T-h/2;

                    FOR i:=1 TO N do

                    begin

                     K3[i]:=PY[i]*h;

                     YY[i]:=Y[i]+K3[i];

                    end;

                     T:=T+h;

                     DERY(T);

                     T:=T-h;

                     FOR i:=1 TO N do

                     begin

                       K4[i]:=PY[i]*h;

                       Y[i]:=Y[i]+(K1[i]+2*K2[i]+2*K3[i]+K4[i])/6;

                     end;

                       T:=T+h;

                       TT:=TT+h;

          end;

               readln;

               CloseGraph;

          end.

        Кнопочку CODE=pas видишь? Это и есть подсветка синтаксиса…

        Сообщение отредактировано: volvo877 — 08.12.09, 17:15

        Guru

        volvo877



        Сообщ.
        #4

        ,
        08.12.09, 17:08

          Moderator

          *******

          Рейтинг (т): 878

          Ну, допустим, уберешь ты ошибку с переполнением (для этого достаточно сделать вот так:

          ExpandedWrap disabled

            {$N+} { <— Делай раз }

            Program TForm1;

            uses Graph;

            type real = extended; { <— Делай два }

            var M1,V1,b,V0:real;

            i1,DR,MO,d:integer;

            { …  все остальное — что и было }

          ), но у тебя же тут же вылетит другая ошибка:

          ExpandedWrap disabled

            PutPixel(t4,y5,6); { <— вот тут, ошибка вылета за границы }

            writeln(out1,f1/0.13,’ ‘,Y[2]*0.13);

          , у тебя ж значения Y5 в Integer не помещаются, как ты собрался отрисовывать-то их?


          nigvil



          Сообщ.
          #5

          ,
          08.12.09, 17:13

            Я попробовал изменить тип Y5 — не помогло.
            А что значения Y5 такие большие получаются?

            Сообщение отредактировано: nigvil — 08.12.09, 17:15

            Guru

            volvo877



            Сообщ.
            #6

            ,
            08.12.09, 17:17

              Moderator

              *******

              Рейтинг (т): 878

              Цитата nigvil @ 08.12.09, 17:13

              Я попробовал изменить тип Y5 — не помогло.

              А чему оно должно помочь? Ты не понял, значение помещается в LongInt, но ведь PutPixel получает Integer, вот тут, при преобразовании LongInt -> Integer у тебя и происходит ошибка. Ты не ответил на вопрос: У тебя размер экрана = 640 X 480. Как ты собираешься выводить точку, Y-координата которой зашкаливает за 32000?

              Добавлено 08.12.09, 17:18

              Цитата nigvil @ 08.12.09, 17:13

              А что значения Y5 такие большие получаются?

              Хм… Ну, ты же их вычисляешь, тебе лучше знать, какие они должны получаться…


              nigvil



              Сообщ.
              #7

              ,
              08.12.09, 17:18

                хммм. я понял. Странно, что y5 такое большое получается….

                да они там в районе десятые — сотые. а тут тысячи…дела блин. буду смотреть.

                Сообщение отредактировано: nigvil — 08.12.09, 17:19


                FasterHarder



                Сообщ.
                #8

                ,
                08.12.09, 20:44

                  Цитата volvo877 @ 08.12.09, 17:08

                  type real = extended; { <— Делай два }

                  я конечно может не понимаю чего то (скорее всего так и есть), но зачем один встроенныи тип заменять другим?..
                  почему нельзя просто прописать :

                  ExpandedWrap disabled

                    var

                       x : extended;

                  Guru

                  volvo877



                  Сообщ.
                  #9

                  ,
                  08.12.09, 21:09

                    Moderator

                    *******

                    Рейтинг (т): 878

                    Цитата FasterHarder @ 08.12.09, 20:44

                    почему нельзя просто прописать :

                    Везде, где встречается ниже по тексту Real, я тоже должен выискивать, и заменять на Extended? Спасибо, я лучше воспользуюсь возможностью, которую язык мне предоставляет, и буду уверен, что везде, где подразумевался real теперь подразумевается Extended…


                    FasterHarder



                    Сообщ.
                    #10

                    ,
                    08.12.09, 21:43

                      Цитата volvo877 @ 08.12.09, 21:09

                      где подразумевался real теперь подразумевается Extended…

                      а, понятно..вот для чего…
                      но тогда перекрыт получается real «навсегда»….
                      в общем, ладно, понятно, какие это дает преимущества…(недостатки вроде тоже есть…может я и ошибаюсь конечно)…

                      Guru

                      volvo877



                      Сообщ.
                      #11

                      ,
                      08.12.09, 21:49

                        Moderator

                        *******

                        Рейтинг (т): 878

                        Цитата FasterHarder @ 08.12.09, 21:43

                        но тогда перекрыт получается real «навсегда»….

                        Чего ж «потерян»? Я не удалил описание типа, я просто его перекрыл. Надо Real (хотя зачем тебе при использовании сопроцессора этот тормоз — непонятно) используй System.Real


                        FasterHarder



                        Сообщ.
                        #12

                        ,
                        08.12.09, 21:51

                          Цитата volvo877 @ 08.12.09, 21:49

                          используй System.Real

                          ох, точно!…ну и я ламер конечно…

                          Topic: [SOLVED] Floating point overflow Message.  (Read 14019 times)

                          Good forum people,

                          When an operation, typically math, exceeds the value within the accuracy limits of the processor, one gets the message «Floating point overflow».

                          Is there a way to trap this error and handle it within one’s own code, so that that message is not displayed, and instead one provides own message on what to do?

                          Thanks!

                          « Last Edit: August 15, 2011, 02:11:20 pm by Elmug »


                          Logged


                          Try this:

                          try
                            //code
                          except
                            on E : Exception do
                             begin
                               //ShowMessage(E.Message); // or ShowMessage(YourMsg);
                              Exit; //break(without msg)
                             end;

                          « Last Edit: August 11, 2011, 08:58:13 am by exdatis »


                          Logged


                          Try this:

                          try
                            //code
                          except
                            on E : Exception do
                             begin
                               //ShowMessage(E.Message); // or ShowMessage(YourMsg);
                              Exit; //break(without msg)
                             end;

                          Thanks, Exdatis.

                          I will try it right away.

                          Looks like what I was after. :)


                          Logged


                          Hi good people,

                          Am back to report on this interesting and important thing relating to the solution kindly afforded by Exdatis.

                          1. No too important, but and «end» not shown is needed in the above code which is part of the Try command. I noticed because Lazarus added it. But mention it here in case it might trip someone else. Good for me Lazarus added it, since it’s the first time I use the Try directive.

                          2. But most important is this: When I hit the run arrow and got it to compile and run, the code DID NOT WORK! No error trapping as expected happened. I did get an error again. Luckily I noticed the error was similar but slightly different than what I was getting without the «Try» directives. And I almost abandoned the solution as not doing what it was supposed to do.

                          3. However, when I tried the .exe file produced at exactly the same time I hit the run arrow (I’m on Windows XP), the code worked PERFECTLY!

                          Therefore, seems to me, there is something to be done to the Lazarus system so that the functioning of the resultant application when Lazarus is running it after a successful compile and when the application (.exe) that it actually produces, have the same behavior, at least for this situation described.

                          I have noticed also similar cases of differences, not as important as this one, concerning what the .exe does and what the application does when it is running from the Run-Arrow, directly after it compiles it. However have not documented them, nor recall details. Vaguely, though, I think they have to do as to when errors happen in execution.

                          Perhaps others have noticed and some action is due by the Lazarus coders?

                          Thanks Exdatis for the help. ;)

                          « Last Edit: August 11, 2011, 10:17:35 am by Elmug »


                          Logged


                          AFAIK even when using a «try» you will still get the error message when running from out of Lazarus, but you should be able to continue the program anyway. 

                          I’m not sure if it is a bug or that in that case you should rather see it as a kind of reminder or warning.   Personally I have become so used to it I hardly notice.


                          Logged

                          1.0/2.6.0  XP SP3 & OS X 10.6.8


                          AFAIK even when using a «try» you will still get the error message when running from out of Lazarus, but you should be able to continue the program anyway. 

                          I’m not sure if it is a bug or that in that case you should rather see it as a kind of reminder or warning.   Personally I have become so used to it I hardly notice.

                          Yes, that’s what it looks like,
                          and I don’t see why the .exe does the error trapping of the Try correctly, and when the same code is run from the GreenRunArrow, no errot trapping takes place.

                          It seems to me that the problem is that Lazarus is using the one and only Errror Message that Free Pascal provides. Meaning Lazarus is a Free Pascal application in itself.

                          Maybe it’s not so easy to solve?

                          Thanks for confirming this, Arbee.


                          Logged


                          Hi good forum people,

                          I did think of an easy way to solve this problem, as follows:

                          1. Why not have Lazarus, upon successful compiling, just run the ACTUAL .exe file, instead of running a variation of it?

                          2. This way, there would be no differences as discussed and confirmed.

                          3. I just don’t see any reason not to run the actual .exe

                          4. Perhaps this is a way to do it like back from DOS when only one .exe would run at a time?

                          5. Also, running the .exe would also alleviate the occasional happening that  an exception raised CAN crash the non-.exe AND  Lazarus. This I have seen happening, while none when the .exe meets exactly the same error.

                          However, I’d like to learn from the thoughts of others on this.

                          Thanks!

                          « Last Edit: August 13, 2011, 12:07:16 pm by Elmug »


                          Logged


                          When running your executable within the compiler, it is running the actual source code — but when your program throws an exception, it is still caught by the debugger (remember — Lazarus is still running in the background).

                            It is just a way of showing you while you are working on your code that a) there is an exception to be handled and b) here are a few more details about the exception; and now you can work on fixing the cause of the exception while still in the development environment.

                            You may not see the error when you just run the executable, because  you may have forgotten or overlooked  showing a message in your try..except block, your program just chugs happily along (or so you think).   Just accept this as a type of double check on your code before you sell millions of copies of your program and have users calling to complain about a bug!!

                          geno.


                          Logged

                          version:      Lazarus 1.9   FPC 3.0.4

                             widget set:  x-86_64-linux-gtk 2
                          OS:             ArchLinux/ Xfce 4.12


                          Sorry, I forgot to mention that if you go into Project —>> Options —>> Linking and deselect all the debugger options, this should take care of the problem.  That is what I have done before.

                          geno.


                          Logged

                          version:      Lazarus 1.9   FPC 3.0.4

                             widget set:  x-86_64-linux-gtk 2
                          OS:             ArchLinux/ Xfce 4.12


                          When running your executable within the compiler, it is running the actual source code — but when your program throws an exception, it is still caught by the debugger (remember — Lazarus is still running in the background).

                            It is just a way of showing you while you are working on your code that a) there is an exception to be handled and b) here are a few more details about the exception; and now you can work on fixing the cause of the exception while still in the development environment.

                            You may not see the error when you just run the executable, because  you may have forgotten or overlooked  showing a message in your try..except block, your program just chugs happily along (or so you think).   Just accept this as a type of double check on your code before you sell millions of copies of your program and have users calling to complain about a bug!!

                          geno.

                          Hi Geno,

                          And thanks for the good points.

                          In my situation, though, I found that the app compiles with no errors and there is no way that while the app is running under the Lazarus umbrella the overflow can be detected.

                          I really can not think of any reason, still, where running the .exe wouldn’t be better than for Lazarus to run it under is umbrella, instead of turning it loose.

                          It seems to me that when Lazarus has compiled it, it’s done its job.

                          And Lazarus does a great job in detecting errors that prevent compiling.

                          Maybe the mode of running it under its umbrella has to do with debugging, single-stepping the app, or some things that I still haven’t gotten to?

                          Also, thanks for the tip on how to set the option you use. I will try it after a while.


                          Logged


                          Понравилась статья? Поделить с друзьями:
                        • Floating point error overflow encountered in exp
                        • Floating point division by zero как исправить delphi
                        • Float object is not subscriptable как исправить
                        • Float object is not iterable python ошибка
                        • Float object is not callable ошибка