处理异常以防止它们首先发生 - C# [英] Handling exceptions vs. Preventing them from occuring in the first place - C#

查看:99
本文介绍了处理异常以防止它们首先发生 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个asp:BoundColumn与DateTime?数据(我将它称为列X)在asp:GridView中。我循环遍历网格中的所有行,并将.Text属性转换为X列到DateTime(如果需要,我需要这样做来检查和更改单元格背景颜色)。



我有2个选项:


  1. 将cast转换为try / catch ...句柄FormatException X被渲染与其中的一些垃圾)...只工作与有效的DateTime值。


  2. 检查列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:

  1. 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.

  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆