Skip to main content
 首页 » 编程设计

c#之异常句柄

2024年02月23日17mfryf

我需要知道这两个异常处理的女巫更好,为什么?或者其他一些做得更好的方法。

try{ 
                if (String.IsNullOrEmpty(filePath)) 
                { 
                    throw new ArgumentNullException("The path is null or empty.", "filePath"); 
                } 

或

 try{ 
                if (String.IsNullOrEmpty(filePath)) 
                { 
                    Console.WriteLine("The path is null or empty"); 
                }  

请您参考如下方法:

我会推荐第二种方法,但在这种情况下您不需要 try/catch。异常用于处理异常 情况。如果您可以使用 if 条件来防止这些情况,您应该更喜欢这个。如果您是性能优化狂热者,您可能已经知道与条件测试相比,抛出和捕获异常的成本更高。