Home computickets How does try ... except work?

How does try … except work?

Author

Date

Category

How does this block work in general? 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
  // Trying to divide an integer by zero - to raise an exception
  try
    zero: = 0;
    number: = 1 div zero;
    ShowMessage ('number / zero =' + IntToStr (number));
  except
    ShowMessage ('Unknown error');
  end;
end;

Answer 1, authority 100%

This is a very useful tool, and also very common. I don’t know how you searched on Google if you didn’t find anything on this topic …

Construction

Try - & gt; EXCEPT - & gt; END

controls the behavior of a possible exception that may 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”. Let’s look at 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!'); // handle a SPECIFIC exception
 end;
end;

There is also another exception handling construct:

TRY - & gt; FINALLY - & gt; 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;
...

2nd case:

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

In both cases, a message will be displayed.


Answer 2

Run your project (exe file) outside Delphi and the block will work. It’s just that the translator catches the error before your block

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions