【发布时间】:2019-03-03 20:42:34
【问题描述】:
在 C# 中执行许多不同的文件处理时,请始终使用如下图所示的 try catch 块。有没有办法将它封装在一个通用类中,所以我不需要重复自己 DRY 。
我想简单地尝试 catch 然后在一个足够灵活的类中处理,我可以向它添加处理程序..
// The caller does not have the required permission.
Catch(UnauthorizedAccessException uae)
{
}
// sourceFileName or destFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
// -or- sourceFileName or destFileName specifies a directory.
Catch(ArgumentException ae)
{
}
// sourceFileName or destFileName is null.
Catch(ArgumentNullException ane)
{
}
// The specified path, file name, or both exceed the system-defined maximum length.
Catch(PathTooLongException ptle)
{
}
// The path specified in sourceFileName or destFileName is invalid (for example, it is on an unmapped drive).
Catch(DirectoryNotFoundException dnfe)
{
}
// sourceFileName was not found.
Catch(FileNotFoundException fnfe
{
}
// destFileName exists. -or- An I/O error has occurred.
Catch(IOException ioe)
{
}
// sourceFileName or destFileName is in an invalid format.
Catch(NotSupportedException nse)
{
}
【问题讨论】:
-
创建一个具有可覆盖方法的基类,并将其放入 try catch 并捕获所有上述异常。类可以继承它并覆盖基方法,异常处理将在基中完成,因为它会冒泡。
-
顺便说一句,您可能想要交换
ArgumentException和ArgumentNullException。ArgumentException是ArgumentNullException的基类,应该拦截所有参数异常。
标签: c# error-handling try-catch dry