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

Your project is not referencing the "MonoAndroid,Version=v8.1" framework. Add a reference to "MonoAndroid,Version=v8.1" in the "frameworks" section of your project.json, and then re-run NuGet restore.

I had  the same problem. Reason: file obj/project.assets.json target "MonoAndroid,Version=v7.1" when my project target androi...