c# exception code example
Example 1: c# throw new exception
static void CopyObject(SampleClass original)
{
if (original == null)
{
throw new System.ArgumentException("Parameter cannot be null", "original");
}
}
Example 2: exception handling c#
try {
} catch( ExceptionName e1 ) {
} catch( ExceptionName e2 ) {
} catch( ExceptionName eN ) {
} finally {
}
Example 3: exception in asp.net c#
try
{
}
catch
{
}
catch (NullReferenceException nullEx)
{
Console.WriteLine(nullEx.Message);
}
catch (InvalidCastException inEx)
{
Console.WriteLine(inEx.Message);
}
Example 4: exception in asp.net c#
try
{
}
catch
{
Console.WriteLine("Exception occurred");
}
catch(Exception ex)
{
Console.WriteLine("Exception occurred");
}
Example 5: exception in asp.net c#
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number: ");
var num = int.parse(Console.ReadLine());
Console.WriteLine($"Squre of {num} is {num * num}");
}
catch(Exception ex)
{
Console.Write("Error info:" + ex.Message);
}
finally
{
Console.Write("Re-try with a different number.");
}
}
}
Example 6: exception in asp.net c#
static void Main(string[] args)
{
var divider = 0;
try
{
try
{
var result = 100/divider;
}
catch(NullReferenceException ex)
{
Console.WriteLine("Inner catch");
}
}
catch
{
Console.WriteLine("Outer catch");
}
}