I've got for example a try/catch in my method:
}
catch (OurCustomExceptionObject1 ex)
{
txtErrorMessage.InnerHtml = "test 1";
}
catch(OurCustomExceptionObject2 ex)
{
txtErrorMessage.InnerHtml = "test 2";
}
catch (OurCustomExceptionObject3 ex)
{
txtErrorMessage.InnerHtml = "test 3";
}
... rest of code here is being executed after the try/catch
I do not want the rest of code to run if any of the exceptions are caught. I'm handling the exceptions. I heard do not use Exit Try for some reason. Is that true, it's bad to do this? Is this the right way to halt execution of code thereafter the catch statement?
If you are wanting to Break execution when an error occurs, then surround your entire sequence or Invoke with the Try/Catch which will cause it to exit outside and begin on the next part of your workflow; you can also use a Throw to force the error when desired to move to the Catch of your exterior Try/Catch.
Code after the try/catch block will not get executed unless the exception is caught by a catch block and not rethrown.
If you use a return statement within a Try/Catch block, there's a behavior you need to be aware of in your code. Consider this block, for example: try { DoSomething(); return; } catch (Exception ex) { // Handle exception here } // code continues here...
Using return to exit a function in javascript Using return is the easiest way to exit a function. You can use return by itself or even return a value.
Either return
in the catch-block, rethrow the exception, or move the code from below the try-block inside the try-block.
Two options immediately come to mind:
return
straight from inside each catch
(as BlueRaja suggested)errorOccurred
) within the catch
blocks for the exceptions you don't want to allow, then put if (errorOccurred) return;
after the whole try/catch blockThe latter might be more readable to other developers, since it's easy to skim past what happens inside a catch
to figure out what happens afterward. Seeing a blatant if (errorOccurred) return;
makes it pretty hard to misunderstand what happened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With