Output from a for loop from a catch block

Finally, performed in this case? I wrote this code and could not decide whether it was really executed in this case or not. I really like some explanations, whatever the answers.

foreach(string s in allStrings) { try { //Error happens here } catch(Exception ex) { //Handle exception break; } finally { //Clean up code } } 
+6
c #
source share
6 answers

You wrote 90% of the code you need to answer this question for yourself.

Keep writing.

+6
source share

Yes. Finally, blocks are always executed when control leaves the corresponding try or catch block. (Unless something super-special happens, such as a crash at runtime or a thread was interrupted.)

+8
source share

Effectively, finally, blocks are ALWAYS called. This is the reason they are named so ...

+2
source share

Based on Matt's answer. This is a complete bust.

I suggest doing something like this and making sure the test passes. MSTest is not the best library for testing, but it is a "Standard" :)

 [TestClass()] public class FinalClauseTester { private TestContext testContextInstance; public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } [TestMethod] [DeploymentItem(@"Something right goes here.")] [DataSource("Something else goes here", "row", somethingOtherSetupCrap)] public void TestFinalClause() { string[] allStrings = {"1", "2", "3", "4", "5"}; int yesCount = 0; foreach(string s in allStrings) { try { //Error happens here throw new Exception(); } catch(Exception ex) { //Handle exception if (yesCount == 3) { break; } } finally { //Clean up code yesCount++; } } // And, at the end of this loop ... Debug.Assert(yesCount = 3); // Or something like this. } } 
+2
source share

Yes it is. Finally, blocks are always executed. See http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html

+1
source share

Yes, he tries to try, and then he catches the catch of the exception, and then, finally, this is what is ultimately caused by both normal execution and the excluded exceptions. I think there is some kind of sharpness hiding somewhere!

+1
source share

All Articles