我刚刚在 Code Complete 中读到,不应使用异常进行流量控制。我还知道,常见的建议是使用异常来处理“异常情况”。但我不确定如何应用这个建议。使用异常来检查构造函数中的无效参数是个好主意吗?例如,我有一个 ExcelInputConverter,它将电子表格中的行转换为 Record 对象(用于操作)。构造函数将 Excel 文件的名称作为输入。我应该使用异常来检查传入的字符串是否是有效的 Excel 文件? excel文件存在吗?看来我应该在这里使用异常,因为如果发生这种情况,该类基本上无法运行。
检查类内或类外的无效数据是个好主意吗?
Public Sub New(filename as string) 'new excel input converter
If Not (Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx") Then Throw New Exception("Can't make an Excel input converter from a non-Excel file like " & inputFileName)
If Not (File.Exists(fileName)) Then Throw New Exception("This file does not exist. Can't make an Excel converter")
最佳答案
如果由于构造函数的参数无效而无法构造对象,则适用异常。大多数语言没有提供不同的方法来告诉对象创建者出了问题(除了在对象上设置“无效”标志之外,我不建议这样做)。
.NET 定义了 ArgumentException对于这种情况。
Is it a good idea to check for invalid data within the class or outside of the class?
该类最有能力了解哪些数据对其有效。如果类随着时间的推移而演变并且有效数据的规则发生变化,您不希望必须去更改使用该类来反射(reflect)该变化的所有代码。
关于oop - 我应该使用异常来检查构造函数中的无效参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11250885/