Net-informations.com
SiteMap  | About    

C# Exception Handling

The C# exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code.

Exception handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards. Exceptions are objects that encapsulate an irregular circumstance, such as when an application is out of memory, a file that cannot be opened, or an attempted illegal cast.

In C# we can handle exceptions with great ease and we can also create our own customized exceptions which can later be used for our applications specific needs. You can also throw an exception from within your own code using the keyword Throw.

  try
  {
	  'your code block
  }
  catch (Exception)
  {
	  'exception handling block
  }
  finally
  {
	  'final cleanup block
  }

The following C# program shows, how to create a custom exception class and how it is using in the program.




using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			try
			{
				int i = 0;
				int j = 0;
				int k = 0;
				j = 10;
				k = 0;
				i = j / k;
			}
			catch (Exception ex)
			{
				throw (new MyCustomException("You cannot divide a number by zeo"));
			}
		}
	}

	public class MyCustomException : System.ApplicationException
	{
		public MyCustomException(string message)
			: base(message)
		{
			MessageBox.Show (message);
		}
	}
}






net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.