csharp Try Catch

// Ordering catch clauses
using System;

class MyClass 
{
	public static void Main() 
	{
		MyClass x = new MyClass();
		try 
		{
			string s = null;
			x.MyFn(s);
		}

		// Most specific:
		catch (ArgumentNullException e) 
		{
			Console.WriteLine("{0} First exception caught.", e);
		}

		// Least specific:
		catch (Exception e) 
		{
			Console.WriteLine("{0} Second exception caught.", e);
		}
		
		// Always runs:
		finally
		{
			//use to Dispose() objects etc.
		}
	}

	public void MyFn(string s) 
	{
		if (s == null) 
		throw new ArgumentNullException();
	}   
}
Example of Try/Catch block with multiple catch to trap specific/general errors, thanks to: MSDN.

Updated: Thursday 14th October 2010, 03:30am

There are 0 comments

Leave a comment of your own

Comments are currently closed.