iT邦幫忙

0

Object reference not set to an instance of an object 問題

是這樣的,今天遇到了這個問題,我加了try catch 後也只顯示這樣

https://ithelp.ithome.com.tw/upload/images/20181121/20110132btvTlkp9sI.jpg

這樣我還是不太清楚錯在哪裡,以下是我的程式碼

 public List<HDOrderListDto> FindAKHistory(string pat_guid, DateTime startDate, DateTime endDate)
        {
            if (String.IsNullOrWhiteSpace(pat_guid)) return null;
            List<HDOrderListDto> dtos = (from x in _repo.HD_ORDER
                         where x.PAT_GUID == pat_guid && x.ODR_DATE >= startDate && x.ODR_DATE <= endDate                       
                         select new HDOrderListDto
                         {                                             
                             OdrDate = x.ODR_DATE,
                             HDType = x.HD_TYPE,
                             AkCode = x.AK_CODE,
                             AkDesc = x.AK_DESC
                         }
                         ).OrderByDescending(x=>x.OdrDate).ToList<HDOrderListDto>();
            try
            {
                foreach (HDOrderListDto dto in dtos)
                {
                    if (dto.AkCode == "OTHER")
                    {
                        dto.AkName= dto.AkDesc;
                        continue;
                    }
                    if (dto.HDType == "HD") dto.AkName = _repo.NCODE.Where(x => x.CID == dto.CID && x.NC_ID == "HDO1001" && x.NC_CODE == dto.AkCode).FirstOrDefault<NCODE>().NC_NAME;
                    if (dto.HDType == "HDF") dto.AkName = _repo.NCODE.Where(x => x.CID == dto.CID && x.NC_ID == "HDO6001" && x.NC_CODE == dto.AkCode).FirstOrDefault<NCODE>().NC_NAME;
                }     
            }
            catch (Exception ex)
            {
                throw ex;
            }
                                     
            return dtos;
        }

想請問我try catch那段該如何下才能讓錯誤顯示得比較清楚?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
暐翰
iT邦大師 1 級 ‧ 2018-11-21 18:07:29
最佳解答

請用小紅點+debug運行,來查看掛在第幾行
2018-11-21.18.10.40-image.png

看更多先前的回應...收起先前的回應...
tenno081 iT邦研究生 4 級 ‧ 2018-11-21 18:10:14 檢舉

你好,第一張圖就是我用中斷點一步一步看之後才出現的結果

暐翰 iT邦大師 1 級 ‧ 2018-11-21 18:15:33 檢舉

tenno081 查看StackTrace可以看出死在第幾行,如圖片
2018-11-21.18.14.26-image.png

小魚 iT邦大師 1 級 ‧ 2018-11-21 19:11:38 檢舉

我都直接ex.ToString()

tenno081 iT邦研究生 4 級 ‧ 2018-11-22 11:35:11 檢舉

是我還不懂得觀察,萬分感謝。

0
小魚
iT邦大師 1 級 ‧ 2018-11-21 19:16:27

這句話的意思就是你有某個object是NULL,
你又想去執行NULL的object,
通常Debug的時候就會停在錯誤的那一行,

另外你加了try catch沒有捕捉到錯誤,
表示你加錯地方了...
正常來說try catch不會跳出這個視窗,
除非你沒有放對地方...
catch到Exception之後將Exception用ToString()轉換可以看到完整的錯誤訊息,
(很長, 但是看久了就習慣了)
就可以大概知道錯在哪裡,
在那邊再下中斷點去找原因..
(當然如果你經驗夠有時候看一下錯誤訊息再看一下程式碼就會知道問題在哪了)

tenno081 iT邦研究生 4 級 ‧ 2018-11-21 19:50:04 檢舉

這樣喔!我有問題的是foreach迴圈那段,把那回圈註解掉就沒問題
所以我才想再迴圈那裏加個try catch看看

小魚 iT邦大師 1 級 ‧ 2018-11-22 07:35:54 檢舉

喔, 我看到你用throw ex了,
可能它把錯誤丟給系統了,
然後就出現錯誤訊息了,
不過一般來說要上線不能這樣寫,
不知道使用者會看到什麼...
所以我們通常是用記Log檔案的方式...

我要發表回答

立即登入回答