From Clomosy Docs
It is a structure used to make programs more secure and resilient against errors. While try...finally blocks are crucial for resource management, try...except blocks are critical for error handling. This structure groups code blocks, enabling the program to handle unexpected situations.
- try: The code written inside this block is for code that carries the potential for errors or may throw exceptions. If an error occurs or an exception is raised while the program is running within this block, control passes to the except block.
- except: This block is used to handle and process errors that occur within the try block. Specific error types can be identified, or a general Exception block can be used to define specific actions for different error situations.
- finally: This block contains code that will be executed regardless of what happens in the try block (whether it runs without errors or encounters an error). Typically, cleanup operations, releasing resources, and similar tasks are defined here.
Try...finally Blocks
try...finally blocks are used to execute a code block whether it completes successfully or not. These blocks are particularly useful for cleanup operations, such as releasing resources.
The code inside the try block will run regardless of whether an error is thrown or not, and the code inside the finally block will execute in all situations.
Example 1
Var Sayi, Sayi2,Toplam : Integer; { Sayi = 20; Sayi2 = 18; try Toplam = Sayi + Sayi2; finally ShowMessage('Toplama işlemi gerçekleştirildi.'); ShowMessage(IntToStr(Sayi)+' + '+IntToStr(Sayi2)+' = '+IntToStr(Toplam)); } }
Example 2
Let's create a code example where a division by zero error is intentionally triggered using the finally clause. Since error handling is not enabled, when finally is used, the program returns the error 'Division by zero when evaluating instruction PushVar ($0,$0,$0,$0,'Result').'.
var number, zero : Integer; { // Try to divide an integer by zero - to raise an exception number = -1; Try zero = 0; number = 1 div zero; ShowMessage('number / zero = '+IntToStr(number)); finally if (number == -1) { ShowMessage('Number was not assigned a value - using default'); number = 0; } } }
Try...except Blocks
When an error occurs in a code block, it is used to catch and handle that error. The except block following the try block is executed when an exception is thrown. This allows the program to handle the error in a more controlled manner.
Example
Let's create an example using the except block to achieve the same result as the example with the try...finally block.
var number, zero : Integer; { // Try to divide an integer by zero - to raise an exception Try zero = 0; number = 1 div zero; ShowMessage('number / zero = '+IntToStr(number)); except ShowMessage('Exception Class: '+LastExceptionClassName+' Exception Message: '+LastExceptionMessage); } }