Lazarus includes an integrated debugger, that makes it easier to find both run-time errors and logic
errors in your application. You can step through code, set breakpoints and watches, and inspect and modify program values.
The "Debug Windows" let you examine the values of variables and some aspects of the state of the program. They are only functional when the program is paused in the debugger.
Proceed as follows:
- Place the cursor in the code editor on the line where you want the program to pause.
- Set a breakpoint by right clicking and selecting Debug / Toggle Breakpoint (or press F5).
An icon will appear to the left of the line:
- Start the program by pressing F9.
When the breakpoint is reached, the execution pauzes.
- Open a debug window, for example: menu View / Debug Windows / Local Variables and inspect the values of some
- When your program is paused, you can step through the code line by line by pressing F7 (or F8 to skip over functions
- Continue at normal speed by pressing F9.
Exceptions: try /except
Runtime errors are more difficult to debug than design time errors.
You should try to intercept runtime errors as much as possible, thus
avoiding confusion of the user.
When a runtime error occurs in an application, such as attempting to divide by zero or an illegal conversion, a so-called exception is "raised".
To handle these exceptions yourself, instead of letting the program
simply crash, precede suspected blocks of code by the keyword try.
Following the try keyword comes a block of code that the program will
test for exceptions. If an exception occurs, the program flow is
interrupted. The sequence of steps taken is as follows:
The program searches for a matching exception handler
- If a handler is found, program control is tranferred to that handler
- If no matching handler is found, the program will show a generic error message and it will terminate
The keyword except marks an exception handling block of code.
L1 := StrToFloat(Edit1.Text);
L2 := StrToFloat(Edit2.Text);
ShowMessage('An invalid number was entered. Please try again.');