2012-12-28 80 views
2

我們經常在我們的方法中使用try catch語句,如果該方法可以返回一個值,但該值不是一個字符串,如何返回異常消息? 例如:嘗試捕捉異常

public int GetFile(string path) 
{ 
    int i; 
    try 
    { 
     //... 
     return i; 
    } 
    catch (Exception ex) 
    { 
     // How to return the ex? 
     // If the return type is a custom class, how to deal with it? 
    } 
} 

如何返回異常?

+1

你不能回到這裏的異常信息。返回一些被理解爲錯誤代碼的int值。或者,拋出調用函數/類可以處理的自定義異常。如果返回類型是一個自定義類,那麼可以發送一個空對象,或者創建一個新的對象,其中包含一些指示出現錯誤的值。 – ryadavilli

+2

只寫「扔」 – Tilak

回答

2

您可以remove如果您想在catch塊中執行某些有用的操作,例如記錄異常,請嘗試使用catch塊來拋出異常或從catch塊中拋出throw異常。如果你想發送異常消息從你的方法和不想拋出異常那麼你可以使用out字符串變量來保存調用方法的異常消息。

public int GetFile(string path, out string error) 
{ 
    error = string.Empty. 
    int i; 
    try 
    { 
     //... 
     return i; 
    } 
    catch(Exception ex) 
    { 
     error = ex.Message; 
     // How to return the ex? 
     // If the return type is a custom class, how to deal with it? 
    } 
} 

如何調用該方法。

string error = string.Empty; 
GetFile("yourpath", out error); 
+0

+1我通常這樣做,如果這種情況非常必要 – horgh

+0

是的,謝謝@Trisped,糾正。 – Adil

2

如果您只是想拋出任何異常,請移除try/catch塊。

如果要處理特定的例外,你有兩個選擇

  1. 只處理那些異常。

    try 
    { 
        //... 
        return i; 
    } 
    catch(IOException iex) 
    { 
    
        // do something 
        throw; 
    } 
    catch(PathTooLongException pex) 
    { 
    
        // do something 
        throw; 
    } 
    
  2. 在通用處理器對於某些類型的

    try 
    { 
        //... 
        return i; 
    } 
    catch(Exception ex) 
    { 
        if (ex is IOException) 
        { 
        // do something 
        } 
        if (ex is PathTooLongException) 
        { 
         // do something 
    
        } 
        throw; 
    } 
    
+3

**不 - 不 - no。**你不應該捕獲*所有*例外,然後檢查類型。顯式捕獲* target *類型,即'catch(IOException)' – abatishchev

+0

你是對的。但有時候,如果要多次應用,這是一個非常大的粗體代碼。在那裏我使用泛型異常處理程序 – Tilak

+0

您可以將共享代碼提取到單獨的方法中以提高重用性。但是的確,異常處理通常是一種具有重複代碼的功能性編程。 – abatishchev

0

你可以直接把你的異常,以及調用方法或事件捕獲了異常做一些事情。

public int GetFile(string path) 
{ 
     int i; 
     try 
     { 
      //... 
      return i; 
     } 
     catch (Exception ex) 
     { 
      throw ex; 
     } 
} 

,並趕上呼籲這樣的方法......

public void callGetFile() 
{ 
     try 
     { 
      int result = GetFile("your file path"); 
     } 
     catch(exception ex) 
     { 
      //Catch your thrown excetion here 
     } 
} 
+3

不要'拋出ex'。只需使用'throw',它不會消除callstack。 – abatishchev