在 .net 中,我如何让编写子类的人知道他们需要为基类可能抛出的特定异常类型编写代码?理想情况下,我希望强制开发人员尝试..捕获异常或在异常发生之前执行必要的验证...我是否可以使用属性来强制开发人员针对异常进行编码?
例如....
我有一些调用“保存”方法的代码。在对象上调用保存之前,我有一个提供一些验证的拦截类。如果一个类不处于有效状态,那么我会抛出一个异常(我正在查看的不是我的代码,所以此时不使用异常不是一个可接受的解决方案......),我想知道的是我如何向我的代码的使用者表明他们应该检查潜在的异常并为其编码或至少执行检查以使异常不会发生...?
所以简单来说(我的代码使用了很多接口(interface)等,所以这只是一个简单的例子......)
class SavableObject {
public static void Save(){
// validation
ValidationClass.BeforeSave();
// then do the save...
DoSave();
}
public static void DoSave(){
// serialize...
}
}
class ValidationClass {
public static void BeforeSave(T cls){
// perform some checks on class T
// THROW EXCEPTION if checks fail
}
}
所以在这个例子中,我的代码的使用者将继承自 SavableObject,如下所示,然后可以调用 save... 例如...
class NewSavableThing: SavableObject
{
public static void Save(){
base.Save();
// calls inherited save method which may throw an exception
// At this point the exception may still occur, and the person writing this
// code may not know that the exception will occur, so the question is how do
// I make this clear or force the developer of this class to code for
// the possibility that the exception may occur?!
}
}
我想知道我是否可以使用一组属性,这样我就可以强制构建子类的人为异常编写代码......例如......
class SavableObject {
[DeveloperMustCatchException(T)] // specifies that the exception type must be caught
public static void Save(){ ... }
}
class NewSaveableThing: SavableObject {
[ExceptionIgnored] / [ExceptionCaught] // specifies that the developer is aware
// that the exception needs catching/dealing with, I am assuming that
// if this attribute is not provided then the compiler will catch
// and prevent a successful compile...
public static void Save() {
}
}
非常感谢任何指点...
编辑:澄清 - 我想强制开发人员承认异常存在,这样开发人员就不能不知道异常。理想情况下,如果缺少 [ExceptionIgnored] 属性或 [ExceptionHandled](或类似)属性,编译器将停止编译......这表明已考虑异常。我不介意异常被忽略,我想做的是确保下一位开发人员知道异常的存在——如果这有意义的话。我知道在///注释中我可以记录异常...
我问是因为我有几个与我们一起工作的学生不知道异常并且没有阅读所有文档,即使异常已记录在案。我无法检查他们编写的每一行代码,所以我希望强制他们承认异常并让编译器检查我是否考虑了异常......他们是否为异常编码是他们的选择,只要他们是意识到它的存在...
最佳答案
使用 XML 文档(方法头中的 ///
注释),特别是 exception tag :
The tag lets you specify which exceptions can be thrown.
足以让人们知道可能会发生异常。他们可以决定捕获它或让它升级。
编辑
事实上,您会喜欢 Java 的 throws
关键字。不幸的是,它does not exist在 C# 中。
关于.Net 子类中的异常捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12124507/