Exceptions — Aspose.Note FOSS for Python API Reference

Иерархия исключений

Все исключения можно импортировать напрямую из aspose.note:

from aspose.note import (
    AsposeNoteError,
    FileCorruptedException,
    IncorrectDocumentStructureException,
    IncorrectPasswordException,
    UnsupportedFileFormatException,
    UnsupportedSaveFormatException,
)

Дерево наследования:

Exception
└── AsposeNoteError
    ├── FileCorruptedException
    ├── IncorrectDocumentStructureException
    ├── IncorrectPasswordException
    ├── UnsupportedFileFormatException
    └── UnsupportedSaveFormatException

AsposeNoteError

ImageRenderOptions: from aspose.note import AsposeNoteError ImageRenderOptions: Exception

Базовый класс для всех исключений Aspose.Note FOSS. Перехватывайте этот класс, чтобы обработать любую ошибку библиотеки независимо от конкретной причины.

from aspose.note import Document, AsposeNoteError

try:
    doc = Document("unknown.one")
except AsposeNoteError as e:
    print(f"Aspose.Note error: {e}")

FileCorruptedException

ImageRenderOptions: from aspose.note import FileCorruptedException ImageRenderOptions: AsposeNoteError

Вызывается, когда .one файл не может быть разобран, потому что его бинарная структура повреждена или некорректна.

Когда вызывается

  • Вызывается Document.__init__ когда парсер файла сталкивается с необратимой бинарной ошибкой.

ImageRenderOptions

from aspose.note import Document, FileCorruptedException

try:
    doc = Document("corrupted.one")
except FileCorruptedException as e:
    print(f"File is corrupted: {e}")

IncorrectDocumentStructureException

ImageRenderOptions: from aspose.note import IncorrectDocumentStructureException ImageRenderOptions: AsposeNoteError

Вызывается, когда структура файла распознана как .one файл, но содержит недопустимую или неподдерживаемую внутреннюю структуру.

Когда вызывается

  • Вызывается Document.__init__ когда файл проходит базовые проверки формата, но имеет структурные проблемы, препятствующие загрузке.

ImageRenderOptions

from aspose.note import Document, IncorrectDocumentStructureException

try:
    doc = Document("unusual.one")
except IncorrectDocumentStructureException as e:
    print(f"Document structure error: {e}")

IncorrectPasswordException

ImageRenderOptions: from aspose.note import IncorrectPasswordException ImageRenderOptions: AsposeNoteError

Возникает, когда LoadOptions.DocumentPassword установлен. Шифрованные (защищённые паролем) документы не поддерживаются в версии v26.3.1.

Когда вызывается

  • Вызывается Document.__init__ когда load_options.DocumentPassword не None.

ImageRenderOptions

from aspose.note import Document, LoadOptions, IncorrectPasswordException

opts = LoadOptions()
opts.DocumentPassword = "secret"

try:
    doc = Document("protected.one", opts)
except IncorrectPasswordException as e:
    print(f"Encryption not supported: {e}")

UnsupportedFileFormatException

ImageRenderOptions: from aspose.note import UnsupportedFileFormatException ImageRenderOptions: AsposeNoteError

Возникает, когда формат файла не распознан как действительный .one файл. Предоставляет a FileFormat атрибут (строка) с обнаруженным или попыткой определить идентификатор формата.

ImageRenderOptions

ImageRenderOptionsImageRenderOptionsImageRenderOptions
FileFormat`strNone`

Когда вызывается

  • Вызывается Document.__init__ когда парсер не может определить файл как поддерживаемый формат OneNote.

ImageRenderOptions

from aspose.note import Document, UnsupportedFileFormatException

try:
    doc = Document("notatonenote.xlsx")
except UnsupportedFileFormatException as e:
    print(f"Unsupported format: {e}")
    if e.FileFormat:
        print(f"Detected format: {e.FileFormat}")

UnsupportedSaveFormatException

ImageRenderOptions: from aspose.note import UnsupportedSaveFormatException ImageRenderOptions: AsposeNoteError

Вызывается, когда Document.Save() вызывается с SaveFormat или классом параметров, который не реализован в v26.3.1. Только SaveFormat.Pdf реализован; все остальные форматы вызывают это исключение.

Когда вызывается

  • Document.Save(target, SaveFormat.One) — Формат кругового обмена OneNote объявлен, но не реализован
  • Document.Save(target, ...) используя любой SaveOptions подкласс, который не PdfSaveOptions

ImageRenderOptions

from aspose.note import Document, SaveFormat, UnsupportedSaveFormatException

doc = Document("MyNotes.one")

try:
    doc.Save("output.one", SaveFormat.One)
except UnsupportedSaveFormatException as e:
    print(f"Save format not supported: {e}")

Отлавливание всех ошибок загрузки

from aspose.note import (
    Document,
    FileCorruptedException,
    IncorrectDocumentStructureException,
    IncorrectPasswordException,
    UnsupportedFileFormatException,
)

def safe_load(path: str) -> Document | None:
    try:
        return Document(path)
    except FileCorruptedException:
        print(f"{path}: file is corrupted")
    except IncorrectDocumentStructureException:
        print(f"{path}: invalid document structure")
    except IncorrectPasswordException:
        print(f"{path}: encrypted documents are not supported")
    except UnsupportedFileFormatException:
        print(f"{path}: format not recognized")
    return None

Отлавливание всех ошибок сохранения

from aspose.note import (
    Document, SaveFormat, UnsupportedSaveFormatException
)

doc = Document("MyNotes.one")

try:
    doc.Save("output.pdf", SaveFormat.Pdf)
except UnsupportedSaveFormatException as e:
    print(f"Cannot save: {e}")

См. также

  • ImageRenderOptions: конструктор вызывает исключения загрузки; Save() вызывает UnsupportedSaveFormatException
  • LoadOptions: настройка DocumentPassword запускает IncorrectPasswordException
  • SaveFormat: только SaveFormat.Pdf реализовано в v26.3.1
 Русский