Try/Catch/Finally

Kurt

Regular
Joined
Feb 14, 2003
Messages
99
Location
Copenhagen
finally

Is the working of the following two pieces of code equivalent(concerning the code that's executed no matter an exception is thrown or not)? Or is there a difference other than pure syntactical dispute?

C#:
namespace Tests
{
	using System;

	public class tryApp
	{
		private static void Main()
		{
			try
			{
				// some code that could throw an exception
			}
			catch
			{
				// handle the exception
			}
			finally
			{
				// run clean up code IN FINALLY BLOCK
			}
		}
	}
}

C#:
namespace Tests
{
	using System;

	public class tryApp2
	{
		private static void Main()
		{
			try
			{
				// some code that could throw an exception
			}
			catch
			{
				// handle the exception
			}
			// run clean up code OUT OF TRY BLOCK
		}
	}
}
 
In the first one the Finally block is always run.

The second one will not if there's an error
 
Last edited:
Both seem to work exactly the same to me

C#:
namespace Tests
{
	using System;

	public class tryApp
	{
		private static void Main()
		{
			try
			{
				Console.WriteLine("Something is about to go wrong");
				int a = 6;
				int b = 0;
				Console.WriteLine("Division = {0}", a/b);
			}
			catch
			{
				Console.WriteLine("Let me handle this");
			}
			finally
			{
				Console.WriteLine("I always run...");
			}
			Console.WriteLine("And does this run?");
		}
	}
}
 
Thanx, I see now... very important when rethrowing exceptions....

C#:
namespace Tests
{
	using System;

	public class tryApp
	{
		private static void Main()
		{
			try
			{
				Console.WriteLine("Something is about to go wrong");
				int a = 6;
				int b = 0;
				Console.WriteLine("Division = {0}", a/b);
			}
			catch
			{
				Console.WriteLine("Let me handle this");
				throw;
			}
			finally
			{
				Console.WriteLine("I always run...");
			}
			Console.WriteLine("And does this run?");
		}
	}
}
 
Hi Robby,

I started this thread under the Systax Related subjects for C#, with thread name 'finally'. It seems to be moved to the general pages, but there it got the thread name "DataView RowFilter Hell". I have been reading on the "DataView RowFilter Hell" thread today, but I did not start that thread, and it handled about complete different subjects. Now, I find our discussion under the general subjects with thread name "DataView RowFilter Hell", of which I would be the thread starter.... Any idea whats going on?
 
Maybe you had accidentaly posted in that thread and a Mod split it into this one.

I have since correvted the title.
 
Back
Top