Exception Handling Mechanism C# with Example



Exception Handling Mechanism C# with Example

 	using System;

	namespace CSharpExceptionHandling
	{
		class Program
		{
			static void Main()
			{
				MyClass MCls = new MyClass();
				try{
					MCls.Method1(); 
				}
				catch (DivideByZeroException e){ 
					Console.WriteLine("{0} in catch clause of Main()", e.Message); 
				}
				finally{ 
					Console.WriteLine("finally clause in Main()"); 
				}
				Console.WriteLine("After try statement in Main.");
				Console.WriteLine(" -- Keep running.");
			}
		}

		class MyClass
		{
			public void Method1()
			{
				try{ 
					Method2(); 
				}
				catch (System.NullReferenceException){ 
					Console.WriteLine("catch clause in Method1()"); }
				finally{ 
					Console.WriteLine("finally clause in Method1()"); }
				}
				
				void Method2()
				{
				int x = 10, y = 0;
				try{ 
					x /= y; 
				}
				catch (System.IndexOutOfRangeException){ 
					Console.WriteLine("catch clause in Method2()"); 
				}
				finally{ 
					Console.WriteLine("finally clause in Method2()"); 
				}
			}
		}
	}
 

0 Comment's

Comment Form