10

あるメソッドからフォームに例外を渡す正しい方法は何だろうと思っています。

public void test()
{
    try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception)
    {
        throw;
    }
}

形:

try
{
    test();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

この方法では、テキスト ボックスが表示されません。

4

3 に答える 3

21

例外の概要だけが必要な場合は、次を使用します。

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

スタック トレース全体を表示したい場合 (通常はデバッグに適しています)、次を使用します。

    try
    {
        test();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

私が時々使用する別の方法は次のとおりです。

    private DoSomthing(int arg1, int arg2, out string errorMessage)
    {
         int result ;
        errorMessage = String.Empty;
        try 
        {           
            //do stuff
            int result = 42;
        }
        catch (Exception ex)
        {

            errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
            result = -1;
        }
        return result;
    }

そして、あなたのフォームには次のようなものがあります:

    string ErrorMessage;
    int result = DoSomthing(1, 2, out ErrorMessage);
    if (!String.IsNullOrEmpty(ErrorMessage))
    {
        MessageBox.Show(ErrorMessage);
    }
于 2013-09-16T09:25:32.317 に答える
1

多くの方法があります。たとえば、次のとおりです。

方法 1:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

方法 2:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}
于 2013-09-16T08:50:57.457 に答える
0
        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }
于 2014-10-01T08:45:36.053 に答える