System.Drawing 中的 GDI+ 错误处理已更新为针对 Status.OutOfMemory 错误引发 ExternalException 而不是 OutOfMemoryException 。
引入的版本
.NET 10 预览版 5
以前的行为
如果 GDI+ 遇到 Status.OutOfMemory 错误(通常是由于输入无效而不是实际的内存问题),System.Drawing API 会引发 OutOfMemoryException。
新行为
从 .NET 10 开始,当 GDI+ 遇到 Status.OutOfMemory 错误时,System.Drawing API 现在引发 ExternalException。
破坏性变更的类型
这是行为 变化。
更改原因
当无法创建内部对象时,GDI+ 并不特别擅长返回错误。 在许多情况下,由于输入无效,对象创建失败,而更高级别的代码获取 null 并将其转换为 Status.OutOfMemory。 这通常是混淆的根源,因为错误通常与实际内存问题无关。
对 ExternalException 的更改提供了更准确的错误报告,因为在其他 System.Drawing 代码路径中,已为类似的 GDI+ 错误抛出了此异常类型。
建议的措施
如果代码在使用 System.Drawing API 时捕获 OutOfMemoryException ,请确保同时捕获 ExternalException 以处理这些 GDI+ 错误。
try
{
    // System.Drawing operations
}
catch (ExternalException ex)
{
    // Handle GDI+ errors (including former OutOfMemoryException cases)
}
catch (OutOfMemoryException ex)
{
    // Handle actual memory issues
}
Try
    ' System.Drawing operations
Catch ex As ExternalException
    ' Handle GDI+ errors (including former OutOfMemoryException cases)
Catch ex As OutOfMemoryException
    ' Handle actual memory issues
End Try
受影响的 API
以前与 GDI+ 交互且可能抛出OutOfMemoryExceptionStatus.OutOfMemory错误的所有 System.Drawing API,包括但不限于:
- System.Drawing.Bitmap 构造函数和方法
 - System.Drawing.Graphics 方法
 - System.Drawing.Image 方法
 - System.Drawing.Icon 构造函数和方法
 - 在内部使用 GDI+ 的其他 System.Drawing 类型