try-catch blocks with the return type

后端 未结 11 1942
半阙折子戏
半阙折子戏 2021-02-07 14:02

If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {  
      //logic here
     return ds.Tables[0];
   }
   catch (Ex         


        
相关标签:
11条回答
  • 2021-02-07 14:53

    You should wrap the caller with a try catch... any exceptions that happen in the routine that is called will bubble out to the caller and you can catch them there.

    Personally, I think it is overkill to have a try catch in this routine as you should have the caller handling the exception.

    For my example, this would be coded as follows...

    private void DoSomething() {
        try {
            DataTable dt = ReturnSomething();
        }
        catch (Exception ex) {
        }    
    }
    
    public DataTable ReturnSomething() {
        DataTable dt = new DataTable();
    
        // logic here
        return dt;
    }
    
    0 讨论(0)
  • 2021-02-07 14:53

    You can do it like the sample code below.

    public DataTable ReturnSomething(out string OutputDesc)
    {
       try
          {
             //logic here
             OutputDesc = string.Format("Your Successful Message Here...");
             return ds.Tables[0];
          }
          catch (Exception e)
          {
             OutputDesc =e.Message;
             return null;
          }
    
    }
    
    0 讨论(0)
  • 2021-02-07 14:54

    Store your return value in a temporary variable like this:

    public DataTable ReturnSomething()
    {
        DataTable returnValue = null;
    
        try
        {
            //logic here
            returnValue = ds.Tables[0]; 
        }
        catch (Exception e)
        {
            ErrorString=e.Message;
        }
    
        return returnValue;
    }
    
    0 讨论(0)
  • 2021-02-07 14:56

    i'd assume you can still set the message, then return null or whatever the c# equivalent is

    public DataTable ReturnSomething(){ 
       try {
            //logic here 
            return ds.Tables[0]; 
       } catch (Exception e) {
            ErrorString=e.Message;
            return null;
       }
    }
    
    0 讨论(0)
  • 2021-02-07 14:57

    You should raise/throw the exception in your catch block and handle it in the calling method.

    public void invokeFaultyCode()
    {
        try
        {
            DataTable dt = ReturnSomething();
        }
        catch(Exception e)
        {
            // Print the error message, cleanup, whatever
        }    
    }
    public DataTable ReturnSomething() throws Exception
    {
       try
       {  
          //logic here
         return ds.Tables[0];
       }
       catch (Exception e)
       {
          ErrorString=e.Message;
          throw;
       }
    }
    

    PS: Sorry for any syntax error, I'm a bit rusty on C#.

    0 讨论(0)
提交回复
热议问题