Skip to main content

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 .... ...."));

Comments

Popular posts from this blog

WPF - Checking Cap Lock Status in WPF

Checking Cap Lock status will be useful in Logon page where we can provide warning to user <Caps Lock is on. Having Caps Lock on may cause you to enter password incorrectly.>

Following sample uses the Control class that is a standard class within the System.Windows.Forms namespace. The DLL containing this namespace is automatically included in Windows Forms applications. The class includes a method named IsKeyLocked, which allows you to determine whether keys such as Caps Lock are switched on or off. To check the status of the Caps Lock key, you can use the method in the following manner:

Example:
privatevoid KeyDownEventHanlder(object sender, KeyEventArgs e)
{
if (Console.CapsLock == true)
{
lblError.Foreground = Brushes.Red;
lblError.Content = "Caps Lock is on.";// Having Caps Lock on may cause you to enter password incorrectly.";

}

else

{
if (lblError.Foreground == Brushes.Red)lblError.Foreground = Brushes.Transparent;
}

}

Error CS0234 The type or namespace name 'ApplicationInsights' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)

Error CS0234 The type or namespace name 'ApplicationInsights' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
To fix this issue run the following command in the Package Manager Console 
Install-Package Microsoft.ApplicationInsights.WindowsApps