核心异常
核心异常
该库通过两种专用的异常类型报告加载和保存失败:PsdLoadException 和 PsdSaveException,它们都扩展标准的 Exception 类。
PsdLoadException
当 Image.Load() / PsdImage.Load() 无法将输入解析为有效的 PSD 或 PSB 文档时抛出。
try
{
using var image = (PsdImage)Image.Load(inputPath);
}
catch (PsdLoadException ex)
{
Console.WriteLine($"Failed to load {inputPath}: {ex.Message}");
}PsdSaveException
当 PsdImage.Save() 无法写出文档时抛出。
try
{
image.Save(outputPath);
}
catch (PsdSaveException ex)
{
Console.WriteLine($"Failed to save {outputPath}: {ex.Message}");
}构造函数
两种异常类型具有相同的双构造函数形式:仅包含消息的构造函数,以及用于包装底层失败的消息加内部异常构造函数。
throw new PsdLoadException("Unexpected end of stream while reading the PSD header.");
throw new PsdSaveException("Failed to write layer data.", innerException);提示与最佳实践
- 在每个处理外部输入的
Image.Load()/PsdImage.Load()调用周围捕获PsdLoadException。 - 如果目标(磁盘、流)可能不可写,请在每个
PsdImage.Save()调用周围捕获PsdSaveException。 - 两种类型都继承自
Exception,因此更宽泛的catch (Exception)也能捕获它们——在想要区分加载失败和保存失败时,请优先使用具体类型。
常见问题
| 问题 | 原因 | 修复 |
|---|---|---|
PsdLoadException 在其他工具能够正常打开的文件上 | 输入不是有效的 PSD/PSB 文档,或使用了此 FOSS 构建的解析器无法识别的功能 | 确认该文件是真正的 PSD/PSB 文档;将不受支持的功能单独报告,而不是与加载失败混在一起 |
在写入流时的 PsdSaveException | 目标流可能不可写,或已被提前释放 | 在调用 Save() 之前,请确认流已打开且可写 |
FAQ
此库在加载或保存失败后会自动重试吗?
不。PsdLoadException 和 PsdSaveException 只会抛出一次,必须由调用方处理;不会自动重试。
我可以检查包装异常的原始原因吗?
是的,在提供时 — 两个构造函数都接受一个 innerException 参数,可通过标准的 Exception.InnerException 属性访问。
API Reference 摘要
| 类/方法 | 描述 |
|---|---|
PsdLoadException(message) / PsdLoadException(message, innerException) | 当文档无法加载时抛出 |
PsdSaveException(message) / PsdSaveException(message, innerException) | 当文档无法保存时抛出 |