Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit Try/Catch to prevent code after from being run

Tags:

c#

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?

like image 640
PositiveGuy Avatar asked Apr 30 '10 21:04

PositiveGuy


People also ask

How do you stop an execution in try catch?

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.

Does code run after try catch?

Code after the try/catch block will not get executed unless the exception is caught by a catch block and not rethrown.

How do I quit try block?

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...

How do you exit a catch block in JavaScript?

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.


2 Answers

Either return in the catch-block, rethrow the exception, or move the code from below the try-block inside the try-block.

like image 57
BlueRaja - Danny Pflughoeft Avatar answered Oct 21 '22 10:10

BlueRaja - Danny Pflughoeft


Two options immediately come to mind:

  1. return straight from inside each catch (as BlueRaja suggested)
  2. set a flag (e.g., errorOccurred) within the catch blocks for the exceptions you don't want to allow, then put if (errorOccurred) return; after the whole try/catch block

The 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.

like image 42
Dan Tao Avatar answered Oct 21 '22 09:10

Dan Tao