第三方代码可正常使用using语句,我的示例却编译报错且异常不一致,求排查
问题描述
我维护的第三方代码库使用如下代码结构:
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook)) { // some additional actions on spreadsheetDocument ... spreadsheetDocument.Close(); }
我希望为无效文件名添加异常处理,编写了如下测试代码:
string docPath = "asd\\da*dw.xlsx" try { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(docPath, SpreadsheetDocumentType.Workbook)) { spreadsheetDocument.Close(); } } catch (DirectoryNotFoundException e) { Console.WriteLine("DirectoryNotFoundException"); }
当我创建控制台应用,将这段代码放入Main方法,以netcoreapp3.1为目标框架运行时,无效文件名会在using语句中抛出DirectoryNotFoundException并被捕获。但在第三方代码库中,相同场景抛出的是ArgumentException而非DirectoryNotFoundException。
查看第三方项目文件,其目标框架为netstandard2.0。当我将自己的测试示例改为目标netstandard2.0时,编译报错:
CS8370 Feature 'using declarations' is not available in C# 7.3. Please use language version 8.0 or greater.
这让我困惑,因为第三方代码库正是以相同方式使用using语句,且未显式设置C#语言版本。
后来发现我的测试示例中存在其他使用using声明的代码:
using FileStream fs = File.Create(filename); { using (StreamWriter writer = new StreamWriter(fs)) { writer.Write("test content"); } }
将这些代码改为传统using块后:
using (FileStream fs = File.Create(filename)) { using (StreamWriter writer = new StreamWriter(fs)) { writer.Write("test content"); } }
测试示例可正常编译,但现在无效文件名会抛出FileNotFoundException,而第三方代码库仍抛出ArgumentException。
疑问
- 第三方代码库可能在哪里设置了C#语言版本?
- 除了语言版本,还有哪些因素会导致这种异常类型的差异?
内容的提问来源于stack exchange,提问作者user32882
相关产品推荐
相关产品推荐

