delphi – How does try … except work?

Question:

How does this block work at all? I found a simple code for its application, tied it to a button, but it gives me an error, something is by zero (as I understand it, the type cannot be divided by zero) and I have to reset the program …

var
    number, zero: Integer;
begin
    // Попытка делить целое число на ноль - чтобы поднять исключение
    try
        zero := 0;
        number := 1 div zero;
        ShowMessage('number / zero = '+IntToStr(number));
    except
        ShowMessage('Неизвестная ошибка');
    end;
end;

Answer:

It is a very useful tool and also very common. I don’t know how you google it if you don’t find anything on this topic …

Design

Try -> EXCEPT -> END

controls the behavior of a possible exception that might occur in the "TRY" section. If this occurs, then the execution of the code in the "TRY" section stops and immediately jumps to the beginning of the "EXCEPT" section and the code located there is executed to the end, that is, to "END". Consider an example of handling the "EZeroDevide" exception (division by zero):

...
var
  a: integer;
  ...
begin
  try
    a := 1/0; 
  except
    on EZeroDivide do showmessage('Divide by zero not allowed!'); // обработка КОНКРЕТНОЙ исключителной ситуации
  end;
end;

There is also another exception handling construct:

TRY -> FINALLY -> END

This block functions a little differently: if an exception occurs in the "TRY" section, the code execution will remain in this section and jump to the "FINALLY" section. But even if no exception occurs, then at the end of the code execution in "TRY", the "FINALLY" section will still be executed. This construction is appropriate to use if at the end of the work it is necessary to perform operations for, for example, freeing memory. Example:

1 case:

...
try
  a := 1/0; 
finally
  showmessage('Divide by zero not allowed!');
end;
...

2 cases:

...
try
  a := 1/1; 
finally
  showmessage('Divide by zero not allowed!');
end;
...

In both cases, a message will be displayed.

Scroll to Top