First attempt at exception handling

So I have the latest Xojo version up and running (2019 r3, Mac OSX El Capitan), and began looking at exception handling. This is in relation to database connection handling, and I noticed the old errorcode and lasterrorcode has now changed.

Previously I called MyDB.Connect and returned the ‘MyDB.errorcode’ or ‘MyDB.databasefile.lasterrorcode’ in a nested If… Then… Else block; if it was zero I worked on the database; if it was non-zero I then called a custom method to provide further information and possible remedial action.

My ‘DBConnect’ method now looks like this (Where zero means success, anything else means we have an issue) :

MyDB = NEW SQLiteDatabase
MyDB.DatabaseFile = GetFolderItem("MyDB.sqlite")

Dim ExceptionValue As Integer = -1

Try
  MyDB.Connect
Catch DBE As DatabaseException
  ExceptionValue = DBE.ErrorNumber
Finally
  Return ExceptionValue
End Try

The other way I found that works is :

MyDB = NEW SQLiteDatabase
MyDB.DatabaseFile = GetFolderItem("MyDB.sqlite")

Try
  MyDB.Connect
Catch DBE As DatabaseException
  Return DBE.ErrorNumber
End Try

Return 0

I also found out that dimming the ‘ExceptionValue’ can’t be done anywhere in the Try… End Try block, irrespective of whether I include Finally or not.

In terms of handling a database exception when connecting, is the above code reasonable ? My preference is the first one because putting ‘Return 0’ outside of the Try… End Try just feels wrong to me.

PS. Please go easy, this is my first attempt at catching exceptions this way!

Your first option won’t work since you’re setting the initial value of ExceptionValue to -1 and it won’t get reset unless there is an error in the connect. That means your return value will never be zero, which you describe as the success value. For your second option

[quote=468099:@Stephen Thomas]Try

MyDB.Connect Catch DBE As DatabaseException ExceptionValue = DBE.ErrorNumber Finally Return ExceptionValue End Try[/quote]
An alternative would be

Try ExceptionValue = 0 MyDB.Connect Catch DBE As DatabaseException ExceptionValue = DBE.ErrorNumber End Try Return ExceptionValue
since if the Connect succeeds the Catch section won’t be executed.

And just to be obtuse, here’s another way.

Try MyDB.Connect Return 0 Catch DBE As DatabaseException Return DBE.ErrorNumber End Try

Thankyou Dale.

I realised about the ExceptionValue not being set after I posted, just like you said, because an exception had not occurred.

I like your second example. One less variable to deal with and everything is contained within the block. I’m going to use that.

Nice example :slight_smile:

Steve