-2

カスタム例外クラスに対するすべての例外を処理したいと考えています。try ブロックでカスタム例外を発生させたくありません。すべての例外がカスタム例外クラスによってキャッチされるようにしたいのです。

私はこれをしたくありません:

private static void Main(string[] args)
{
    try
    {
        Console.WriteLine("Exception");
        throw new CustomException("Hello World");
    }
    catch (CustomException ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}

これ欲しい:

private static void Main(string[] args)
{
    try
    {
        Console.WriteLine("Exception");
        throw new Exception("Hello World");
    }
    catch (CustomException ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}

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

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

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

    protected CustomException(SerializationInfo info, StreamingContext context) 
        : base(info, context)
    {
    }
}

あなたが私の質問を理解してくれることを願っています。

4

2 に答える 2

2

既存の例外クラスは変更できません。

ただし、例外をキャッチして CustomException に変換することはできます。

try
{
    try
    {
        // Do you thing.
    }
    catch(Exception e)
    {
        throw new CustomException("I catched this: " + e.Message, e);
    }
}
catch(CustomException e)
{
    // Do your exception handling here.
}

これがあなたの望みかどうかはわかりませんが、これがあなたができる最も近い方法だと思います。

于 2013-10-11T07:54:36.333 に答える
1

すべての例外を CustomException であるかのように扱いたいため、これを実現したいと考えています。では、すべての例外をそのように扱ってみませんか? CustomException を処理するのと同じ方法で、すべての例外を処理します。CustomException として処理したくない例外がいくつかある場合、達成したいことは問題ではありません。

どうしてもすべてを CustomException として扱わなければならない場合は、次のようにすることができます。

try
{
   //Something that causes any form of exception
}
catch (Exception ex)
{
   throw new CustomException(ex.Message); //Caught and handled in another place.
}

しかし、それは賢明な方法ではないと思います。

于 2013-10-11T07:49:05.930 に答える