Try and Catch

Guardian17

Active Member
Licensed User
Longtime User
After several months of using this forum, only just came across the use of "Try" and "Catch" to "catch" Exceptions.

I could only find the definitions of "Try" and "Catch" in the Keyword definitions, but little is said about them other than catching Exceptions.

Is there a tutorial on "Try" and "Catch" that better explains HOW and WHY they are used? Is it only for debugging purposes? Can "Try" and "Catch" be left in any final Released .apk application files?
 

NJDude

Expert
Licensed User
Longtime User
That's the purpose of Try...Catch to catch exceptions and allow you, the developer, to take action when these exceptions occur as opposed to let the system display an error message to the user.

You can type "try catch" in the search box and look at the sample code.
 
Upvote 0

DKCERT

Member
Licensed User
Longtime User
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim i As Int
   Dim s, sTest As String
   ' The following will throw an exeption as the
   ' sTest string is zero based (0|1|2|3) and we
   ' try to get a char (pos=4) further than it is.
   Try
      sTest = "TEST"
      For i = 0 To sTest.Length ' Should be: sTest.Length-1
         s = s & sTest.CharAt(i)
      Next
   Catch
      ToastMessageShow("Woops... something went wrong!",False)
   End Try
   Activity.Finish
End Sub
 
Last edited:
Upvote 0

Guardian17

Active Member
Licensed User
Longtime User
Clarification

Thanks for the example.

Will this catch ALL Exceptions regardless of where they occur in an App, or only in the "area" defined by the Try and Catch?

If your example was the only Try and Catch in an App, but the App also performed reading and writing of text files, and a "File Not Found" Exception was thrown, (outside of the Example code), will that also cause your example Toast message to appear?
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
No. That will only catch the exception (error) in the code between the Try-Catch. For other exceptions, you need to trap them individually, using similar code.
 
Upvote 0
Top