Skip to main content
 首页 » 编程设计

c#之如何在特定类的 NullReferenceException 上自动抛出自定义异常

2024年02月05日11mq0036

public class Dog  
{ 
 
    public string Name { get; set;} 
} 

然后在这种情况下 null 被传递给 FeedDog()

public void FeedDog(Dog dog) 
{ 
 
    Console.WriteLine("Feeding "+dog.Name); // throws NullReferenceException 
} 

我该怎么做才能在不执行此操作的情况下抛出 DogDoesNotExistException

public void FeedDog(Dog dog) 
{ 
 
    if (dog == null) 
        throw new DogDoesNotExistException(); // want to get rid of this 
    Console.WriteLine("Feeding "+dog.Name); 
} 

所以当你这样做的时候

public void FeedDog(Dog dog) 
{ 
 
    Console.WriteLine("Feeding "+dog.Name); // throws DogDoesNotExistException 
} 

请您参考如下方法:

一种方法是捕获 global error handler 中的错误并从那里重新抛出,但这会影响每个类(class)。

因此您应该考虑使用 AOP(请参阅 what-is-aspect-oriented-programming)。

例如,如果你正在使用依赖注入(inject),你可以使用拦截器

http://docs.autofac.org/en/latest/advanced/interceptors.html

这个额外的类将包装每个方法调用。带有重新抛出的 try catch 逻辑可以放置在那里。如果您真的想这样做,我建议将原始异常添加为内部异常。

如果您正在使用 MVC,您还可以使用过滤器属性。

综上所述,我会小心捕获像这样的 Null Ref 错误,因为它们非常普遍。