处理异常以防止它们首先发生 - C# [英] Handling exceptions vs. Preventing them from occuring in the first place - C#
问题描述
我有2个选项:
-
将cast转换为try / catch ...句柄FormatException X被渲染与其中的一些垃圾)...只工作与有效的DateTime值。
-
检查列X以确保它是
在
套上的正确格式(如何?),只有格式是
确定。
我应该采取哪种方式,为什么?
谢谢。
ps 1加入所有解释,TryParse接受的答案
Edit2:即使我使用TryParse,我已经取消选中接受的答案继续讨论。
我的好数据/坏数据比例约为2/1 - 这意味着很多不好的输入
如果没有其他的话,我会在几天内重新接受答案。
你可以做第二个选项。 DateTime.TryParse可以帮助。
I have a asp:BoundColumn with DateTime? data (i'll call it column X) in the asp:GridView. I loop through all the rows in the grid, and cast the .Text property to column X to DateTime (i need this to do some checking and change the cell background color if needed).
I have 2 options:
wrap the cast in try/catch ... handle FormatException (in case column X gets rendered with some junk in it) ... and work only with valid DateTime values.
check the column X to make sure it's in the correct format (how?) before casing, and only cast if format is ok.
Which approach should i take, and why?
Thank you.
p.s. 1 up-vote for all explanations, accepted answer for TryParse
Edit2: even though i used TryParse, I've unchecked the accepted answer to keep the discussion going.
My "good data"/"bad data" ratio is about 2/1 - this means lots of bad input
I'll re-accept the answer in a couple of days, if nothing else comes up.
You could do the 2nd option. DateTime.TryParse can help.
这篇关于处理异常以防止它们首先发生 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!