try-catch blocks with the return type

后端 未结 11 1943
半阙折子戏
半阙折子戏 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: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#.

提交回复
热议问题