23

C# で独自の Exception クラスを実装しようとしています。この目的のために、Exception から派生した CustomException クラスを作成しました。

class CustomException : Exception
{
    public CustomException()
        : base() { }

    public CustomException(string message)
        : base(message) { }

    public CustomException(string format, params object[] args)
        : base(string.Format(format, args)) { }

    public CustomException(string message, Exception innerException)
        : base(message, innerException) { }

    public CustomException(string format, Exception innerException, params object[] args)
        : base(string.Format(format, args), innerException) { }
}

それから私はそれを使用します

static void Main(string[] args)
{
    try
    {
        var zero = 0;
        var s = 2 / zero;
    }
    catch (CustomException ex)
    {
        Console.Write("Exception");
        Console.ReadKey();
    }
}

例外が発生することを期待していますが、取得できるのは標準の DivideByZeroException だけです。CustomException クラスを使用してゼロ除算の例外をキャッチするにはどうすればよいですか? ありがとう。

4

2 に答える 2

29

既存のコードによってスローされる例外の種類を魔法のように変更することはできません。

throwそれをキャッチできるようにするには、例外が必要です。

try 
{
   try
    {
        var zero = 0;
        var s = 2 / zero;
    }
    catch (DivideByZeroException ex)
    { 
        // catch and convert exception
        throw new CustomException("Divide by Zero!!!!");
    }
}
catch (CustomException ex)
{
    Console.Write("Exception");
    Console.ReadKey();
}
于 2013-04-13T21:14:44.423 に答える
17

まず、独自の例外を確認したい場合はthrow、コードのどこかでそれを行う必要があります。

public static int DivideBy(this int x, int y)
{
    if (y == 0)
    {
        throw new CustomException("divide by zero");
    }

   return x/y; 

}

それから:

int a = 5;
int b = 0;
try
{
      a.DivideBy(b);
}
catch(CustomException)
{
//....
}
于 2013-04-13T21:16:49.067 に答える