Show message box in case of exception

后端 未结 3 1096
孤独总比滥情好
孤独总比滥情好 2020-12-14 12:07

I\'m wondering what the correct way is to pass on an exception from one method to my form.

public void test()
{
    try
    {
        int num = int.Parse(\"g         


        
相关标签:
3条回答
  • 2020-12-14 12:19

    There are many ways, for example:

    Method one:

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

    Method two:

    public void test(ref string ErrMsg )
    {
    
        ErrMsg = string.Empty;
         try
            {
                int num = int.Parse("gagw");
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message;
            }
    }
    
    0 讨论(0)
  • 2020-12-14 12:27
            try
            {
               // your code
            }
            catch (Exception w)
            {
                MessageDialog msgDialog = new MessageDialog(w.ToString());
            }
    
    0 讨论(0)
  • 2020-12-14 12:30

    If you want just the summary of the exception use:

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

    If you want to see the whole stack trace (usually better for debugging) use:

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

    Another method I sometime use is:

        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;
        }
    

    And In your form you will have something like:

        string ErrorMessage;
        int result = DoSomthing(1, 2, out ErrorMessage);
        if (!String.IsNullOrEmpty(ErrorMessage))
        {
            MessageBox.Show(ErrorMessage);
        }
    
    0 讨论(0)
提交回复
热议问题