Derive custom exception types

  • Thread starter Thread starter p988
  • Start date Start date
P

p988

Could someone show me how to derive and use custom exception types
separately from:System.Exception, System.Object and
System.ApplicationException in C#?

When people say:"Use Visual Studio .NET to create a component..." What does
it mean by "component" here in C#?
 
You should create your own class, hat derives from System.SystemException
and override the appropriate members.
 
Here is a working example (console application) that deomonstrates what you
want to know...

/* Copyright 2003 O'Reilly - used with permission from source code for
Programming C# 3rd Edition by Jesse Liberty */

namespace Programming_CSharp
{
using System;

public class MyCustomException :
System.ApplicationException
{
public MyCustomException(string message):
base(message)
{

}
}

public class Test
{
public static void Main( )
{
Test t = new Test( );
t.TestFunc( );
}

// try to divide two numbers
// handle possible exceptions
public void TestFunc( )
{
try
{
Console.WriteLine("Open file here");
double a = 0;
double b = 5;
Console.WriteLine ("{0} / {1} = {2}",
a, b, DoDivide(a,b));
Console.WriteLine (
"This line may or may not print");
}

// most derived exception type first
catch (System.DivideByZeroException e)
{
Console.WriteLine(
"\nDivideByZeroException! Msg: {0}",
e.Message);
Console.WriteLine(
"\nHelpLink: {0}\n", e.HelpLink);
}
catch (MyCustomException e)
{
Console.WriteLine(
"\nMyCustomException! Msg: {0}",
e.Message);
Console.WriteLine(
"\nHelpLink: {0}\n", e.HelpLink);
}
catch
{
Console.WriteLine(
"Unknown exception caught");
}
finally
{
Console.WriteLine ("Close file here.");
}

}

// do the division if legal
public double DoDivide(double a, double b)
{
if (b == 0)
{
DivideByZeroException e =
new DivideByZeroException( );
e.HelpLink=
"http://www.libertyassociates.com";
throw e;
}
if (a == 0)
{
MyCustomException e =
new MyCustomException(
"Can't have zero divisor");
e.HelpLink =
"http://www.libertyassociates.com/NoZeroDivisor.htm";
throw e;
}
return a/b;
}
}
}
 
When you do this, you should make sure that you create the following
constructors:

1) The usual constructor that you'd use to create the exception.
2) A constructor that takes an inner exception, so that you can use this
exception to wrap other exceptions
3) A serialization constructor (and make the exception serializable). This
allows it to pass across through remoting.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Telmo Sampaio said:
You should create your own class, hat derives from System.SystemException
and override the appropriate members.

Err no, you should really derive from ApplicationException. This class is
used to differentiate between exceptions thrown by an application versus the
system

andrew
 
Back
Top