C# Exception Exception(String)

Description

Exception Exception(String) initializes a new instance of the Exception class with a specified error message.

Syntax

Exception.Exception(String) has the following syntax.


public Exception(
  string message
)

Parameters

Exception.Exception(String) has the following parameters.

  • message - The message that describes the error.

Example

The code demonstrates the use of the constructor that takes a caller-specified message as a parameter, for both the derived class and the base Exception class.


/*from w  w  w.j av  a2s .  com*/
using System;
class NotEvenException : Exception
{
    const string notEvenMessage =
        "The argument to a function requiring " +
        "even input is not divisible by 2.";

    public NotEvenException() :
        base(notEvenMessage)
    { }

    public NotEvenException(string auxMessage) :
        base(String.Format("{0} - {1}",
          auxMessage, notEvenMessage))
    { }
}

class NewSExceptionDemo
{
    public static void Main()
    {
        try
        {
            throw new Exception(String.Format(
                "The argument {0} is not divisible by 2.",
                ""));
            throw new NotEvenException(
                String.Format("Invalid argument: {0}", ""));

            int halfInput = 0;
            Console.WriteLine(
                "Half of {0} is {1}.", "", halfInput);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version