How to use a try/catch/finally

354 views
Skip to first unread message

Hamza BENDHIBA

unread,
Mar 16, 2023, 1:58:35 AM3/16/23
to Harbour Users
Hello,

I would like to use the try catch functionality in a function.

Here is an example of a code : 

PROCEDURE TestTry()
    LOCAL nFileHandle

    TRY
        // Try to open a file
        nFileHandle := FOPEN("non_existent_file.txt", "r")
        // If the file does not exist, an exception will be thrown
    CATCH
        // Handle the exception
        MSGINFO(NULL, "File not found!", "Error", MB_OK)
    FINALLY
        // Close the file handle, whether an exception occurred or not
        FCLOSE(nFileHandle)
    ENDTRY

RETURN

But I have an error on the line of the try command : 
Error E0020 Incomplete statement or unbalanced delimiters

Do you have same exemple of try catch that work in harbour ?

Regards.

Hamza B


Pete

unread,
Mar 16, 2023, 3:57:42 AM3/16/23
to Harbour Users
Hello,

change : ENDTRY --> END

Also, check and (if you don't already have done) include:
#include "hbcompat.ch" on top of your source
and `xhb.hbc` into your .hbp

regards,
Pete

ivanil.m...@gmail.com

unread,
Mar 16, 2023, 7:46:19 AM3/16/23
to Harbour Users
Hello Friend;

Even fixing the Try ; Catch ; End ; you won't be able to test the code because fopen doesn't throw an error; look:

Captura de tela 2023-03-16 084415.png

To force the test, check if nFileHandle is less than zero, if less call break;

Pete

unread,
Mar 16, 2023, 1:07:22 PM3/16/23
to Harbour Users
Hi,
Your assertion about efficient utilization of FOpen() may be correct,
however, my reply did not focus on that, I just tried to show a way
to resolve the compilation error. For the validity and/or effectiveness
of code, responsible is solely the coder. ;-)

regards,
Pete

ivanil.m...@gmail.com

unread,
Mar 16, 2023, 1:29:01 PM3/16/23
to Harbour Users
Hello Pete;

It was not my intention to offend you; it was not directed at you; your answer is correct;
I just wanted to show Hamza that the code won't serve the intended purpose of testing try; just a complement to your answer without taking away its merits.

Big hug

Carlos Murúa

unread,
Mar 17, 2023, 4:08:59 PM3/17/23
to Harbour Users
As far as I know Harbor has a different synaxis for error handling as shown in this link:
https://harbour.github.io/doc/clc53.html#begin-sequence-cmd

But using compilation directives you can change the syntax, like this:

# xcommand TRY => bError := errorBlock( {|oErr| break( oErr ) } ) ;;
BEGIN SEQUENCE
# xcommand CATCH [<!oErr!>] => errorBlock( bError ) ;;
RECOVER[ USING < oErr > ] <- oErr->;;
ErrorBlock( bError )

Carlos Murúa

unread,
Mar 17, 2023, 4:20:06 PM3/17/23
to Harbour Users

Carlos Murúa

unread,
Mar 21, 2023, 12:05:23 PM3/21/23
to Harbour Users
This is the better method !
Reply all
Reply to author
Forward
0 new messages