.NET Tip: Exiting a Try/Catch Block


Application Security Testing: An Integral Part of DevOps

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 {
catch (Exception ex)
   // Handle exception here

// code continues here...

Assuming no exception is generated, the return statement will fire normally and the code flow will go back to whatever routine called this block of code. Adding a Finally section to this block of code, however, can lead to confusion. Take this code, for example:

try {
   Console.WriteLine("In try block");
catch (Exception ex)
   Console.WriteLine("In finally block");

Even though the return statement normally will send you back to the calling block of code, the finally block always executes. For this snippet, the output will look like this:

In try block
In finally block

This behavior is by design, but it's just something to remember if you're using finally blocks along with return statements in your exception handling.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic. Send him your questions and feedback via e-mail at questions@techniquescentral.com.


  • try catch block problem

    Posted by c++_help on 11/07/2008 07:07am

    I have written following prog in c++ #include #include using namespace std; int main() { int a,b; cout<<"Enter values of a & b\n"; cin>>a; cin>>b; int x=a-b; try { if(x !=0) { cout<<"Result(a/x)="< Reply

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.