Throw an Exception?

canalrun

Well-Known Member
Licensed User
Longtime User
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

Thanks,
Barry.
 

kickaha

Well-Known Member
Licensed User
Longtime User
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.
 
Upvote 0

canalrun

Well-Known Member
Licensed User
Longtime User
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.

Thanks,
Barry.
 
Upvote 0

mc73

Well-Known Member
Licensed User
Longtime User
Perhaps, using a flag would do it? For example,

B4X:
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

I don't know, just a thought.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…