我试图将我的异常抛出逻辑包装到另一个类中,以便更容易抛出自定义异常。每个类都将使用对此 Thrower 类的直接引用或接口(interface),无论哪种最合适。
我已经编写了一个简单的类来处理它并且它在大部分情况下都有效,但是我在具有返回类型的方法中遇到了一种情况,即使总是会抛出异常,编译器也无法检测到它并提示并非所有路径都返回一个值。
以下代码显示了 Thrower 类和任何将使用所述 Thrower 的类的结构的简化形式。
public class Thrower
{
public void ThrowException()
{
throw new Exception("Im an exception");
}
}
public class Foo
{
// Does not work, compiler complains about not all paths returning values.
public int ExceptionNotDetected(bool shouldThrow)
{
if (!shouldThrow)
{
return 1;
}
var thrower = new Thrower();
thrower.ThrowException();
}
// Works fine.
public int ExceptionDetected(bool shouldThrow)
{
if (!shouldThrow)
{
return 1;
}
throw new Exception("Im an exception");
}
}
据我所知,使用 Thrower 的方法必须返回值或抛出异常。由此看来,方法 ExceptionNotDetected 和 ExceptionDetected 在功能上是等效的。
为什么编译器会提示 ExceptionNotDetected?
编辑:
关于设计,这纯粹是为了说明目的,因为我真正想做的就是了解正在发生的事情。如果我在帖子描述中没有正确澄清这一点,我深表歉意。话虽如此,我很欣赏有关结构的建议。
最佳答案
编译器只能看到当前方法的返回类型,“ThrowExeption()”方法不返回任何内容(void)。
它不会检查被调用的方法内部是否会返回异常。
关于c# - 为什么编译器检测不到这里会抛出异常呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57381609/