Hello,
I would like to throw an exception as a means of breaking out of a series of loops as a check for something totally unexpected. I could not find an example or if this is even possible.
Here is some "dream" code. Is something like this possible in B4A? What is the correct syntax?
B4X:
Try
.....
.....
.....
If (x < 0) Then Throw
.....
.....
.....
Catch
Log("This will never work.")
End Try
Why not seperate the block of loops into a function, and then to break out of them all you need to do is return. You can use a return value to check if it returned due to an error.
Thanks.
Using ExceptionEx is the solution. I found a quick example embedded in code intended as a threading example – very helpful.
I have a bunch of nested loops within a subroutine. If I get an interim result that is negative, this physically makes no sense. I have to abort and exit the subroutine. This is actually a case when Goto's are useful, but using an Exception and Throw is a more structured solution.
do while flagError=false and flagFinalResult=false
if x<0 then
flagerror=true
else
'continue
flagFinalResult=true
end if
loop
if flagerrror=true then
return
else
'continue
end if