2012-08-02 34 views
0

我在visual studio(成功)中構建我的解決方案,我試圖運行它,但由於某種原因,在下面的代碼行拋出異常我去了幾篇文章,但有沒有確切的解決方案如何處理用戶代碼未處理的空引用異常

public static int GetCurrentPolicyClassId() 
    { 
     **int policyClassId = (int) HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID];** 
     return policyClassId; 
    } 
+1

有些東西在那裏......把一個斷點放在那一行上,然後你可以看看數據發生了什麼。 – Alex 2012-08-02 14:56:20

回答

3

您調用的鏈中的一個值爲null。你只需要獲取值前檢查:

if(HttpContext != null && 
    HttpContext.Current != null && 
    HttpContext.Current.Session != null && 
    HttpContext.Current.Session[AppConstants.SK_POLICYCLASSID] != null) 
{ 
    // Get the value here. 
} 
else 
{ 
    // Something was null. Either set a default value or throw an Exception 
} 
0

你或許應該檢查是否HttpContext != null && HttpContext.Current != null && HttpContext.Current.Session != null

0

任何異常被try/catch(或finally)處理,如果該異常有可能在一般的處理。

例如StackOverflowException無法處理。

您需要:

  • 異常的類型是
  • 理解的原因吧
  • 在此基礎上決定是否該異常是在你的應用程序
  • 如果異常行爲是,如果程序需要處理它,或者離開程序失敗,則使用try/catch來處理它,因爲接收到的異常太危險了,最好讓所有的東西都失敗。
  • 如果這不是異常行爲,嘗試處理它,例如null檢查,或任何...

希望這有助於。

相關問題