Saturday, September 3, 2011

Creating and Throwing Exceptions in c#

Main purpose of using an exception is to indicate error while running a program.

Excepton can be used for following conditions:

Note: Following sample is from MSDN

1) When method cannot completely define its funcionality

static void CopyObject(SampleClass original)
{
if (original == null)
{
throw new System.ArgumentException("Parameter cannot be null", "title");
}


}

2)If inapporiate call to an object is made

class ProgramLog
{
System.IO.FileStream logFile = null;
void OpenLog(System.IO.FileInfo fileName, System.IO.FileMode mode) {}


void WriteLog()
{
if (!this.logFile.CanWrite)
{
throw new System.InvalidOperationException("Logfile cannot be read-only");
}
// Else write data to the log and return.
}
}


3) When an argument to a method causes an exception

static int GetValueFromArray(int[] array, int index)
{
try
{
return array[index];
}
catch (System.IndexOutOfRangeException ex)
{
System.ArgumentException argEx = new System.ArgumentException("Index is out of range", "index", ex);
throw argEx;
}
}


4. Raise an exception

throw (new Exception("there is error in .... ...."));

No comments:

Post a Comment

Open default email app in .NET MAUI

Sample Code:  if (Email.Default.IsComposeSupported) {     string subject = "Hello!";     string body = "Excellent!";    ...