> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/microsoft/markitdown/llms.txt
> Use this file to discover all available pages before exploring further.

# Exceptions

> Exception classes used in MarkItDown for error handling

MarkItDown defines a hierarchy of exception classes to handle various error scenarios during file conversion. All MarkItDown-specific exceptions inherit from the base `MarkItDownException` class.

## Exception Hierarchy

```
MarkItDownException (base)
├── MissingDependencyException
├── UnsupportedFormatException
└── FileConversionException
```

## Exception Classes

<AccordionGroup>
  <Accordion title="MarkItDownException" icon="exclamation-triangle">
    ### MarkItDownException

    Base exception class for all MarkItDown-specific exceptions.

    #### Inheritance

    Inherits from Python's built-in `Exception` class.

    #### Usage

    This is the base class for all MarkItDown exceptions. You can catch this exception to handle any MarkItDown-related error.

    #### Example

    ```python theme={null}
    from markitdown import MarkItDown, MarkItDownException

    converter = MarkItDown()

    try:
        result = converter.convert("document.pdf")
    except MarkItDownException as e:
        print(f"MarkItDown error occurred: {e}")
    ```
  </Accordion>

  <Accordion title="MissingDependencyException" icon="puzzle-piece">
    ### MissingDependencyException

    Raised when a converter recognizes a file format but the required optional dependencies are not installed.

    #### Inheritance

    Inherits from `MarkItDownException`.

    #### When Raised

    This exception is thrown when:

    * A converter's `convert()` method is called
    * The converter recognizes the file format
    * Required optional dependencies for that format are not installed

    <Note>
      This is not necessarily a fatal error. The converter will be skipped, and MarkItDown will try other converters. An error only bubbles up if no suitable converter is found.
    </Note>

    #### Error Message Format

    The error message clearly indicates which dependency is missing and provides installation instructions:

    ```
    {converter} recognized the input as a potential {extension} file, but the 
    dependencies needed to read {extension} files have not been installed. 
    To resolve this error, include the optional dependency [{feature}] or [all] 
    when installing MarkItDown. For example:

    * pip install markitdown[{feature}]
    * pip install markitdown[all]
    * pip install markitdown[{feature}, ...]
    * etc.
    ```

    #### Example

    ```python theme={null}
    from markitdown import MarkItDown
    from markitdown._exceptions import MissingDependencyException

    converter = MarkItDown()

    try:
        # Attempting to convert an Excel file without pandas installed
        result = converter.convert("data.xlsx")
    except MissingDependencyException as e:
        print(f"Missing dependency: {e}")
        print("Please install the required dependencies")
    ```
  </Accordion>

  <Accordion title="UnsupportedFormatException" icon="file-slash">
    ### UnsupportedFormatException

    Raised when no suitable converter was found for the given file.

    #### Inheritance

    Inherits from `MarkItDownException`.

    #### When Raised

    This exception is thrown when:

    * MarkItDown has tried all available converters
    * None of the converters support the file format
    * The file extension or content type is not recognized

    #### Example

    ```python theme={null}
    from markitdown import MarkItDown
    from markitdown._exceptions import UnsupportedFormatException

    converter = MarkItDown()

    try:
        # Attempting to convert an unsupported file format
        result = converter.convert("document.xyz")
    except UnsupportedFormatException as e:
        print(f"Unsupported format: {e}")
        print("This file format is not supported by MarkItDown")
    ```
  </Accordion>

  <Accordion title="FileConversionException" icon="file-circle-xmark">
    ### FileConversionException

    Raised when a suitable converter was found, but the conversion process fails.

    #### Inheritance

    Inherits from `MarkItDownException`.

    #### Constructor Parameters

    | Parameter  | Type                                      | Default | Description                                                                           |
    | ---------- | ----------------------------------------- | ------- | ------------------------------------------------------------------------------------- |
    | `message`  | `Optional[str]`                           | `None`  | Custom error message. If not provided, a message is auto-generated based on attempts. |
    | `attempts` | `Optional[List[FailedConversionAttempt]]` | `None`  | List of failed conversion attempts with details about each failure.                   |

    #### Attributes

    | Attribute  | Type                                      | Description                                                                               |
    | ---------- | ----------------------------------------- | ----------------------------------------------------------------------------------------- |
    | `attempts` | `Optional[List[FailedConversionAttempt]]` | List of failed conversion attempts, each containing converter info and exception details. |

    #### When Raised

    This exception is thrown when:

    * A suitable converter was found for the file
    * The conversion process started but failed
    * The file may be corrupted or have unexpected content

    #### Auto-Generated Error Messages

    If no message is provided:

    * Without attempts: `"File conversion failed."`
    * With attempts: Detailed message listing each failed attempt with converter name and error details

    #### Example

    ```python theme={null}
    from markitdown import MarkItDown
    from markitdown._exceptions import FileConversionException

    converter = MarkItDown()

    try:
        # Attempting to convert a corrupted or malformed file
        result = converter.convert("corrupted.pdf")
    except FileConversionException as e:
        print(f"Conversion failed: {e}")
        
        # Access failed attempts if available
        if e.attempts:
            print(f"Number of attempts: {len(e.attempts)}")
            for attempt in e.attempts:
                print(f"  - Converter: {type(attempt.converter).__name__}")
                if attempt.exc_info:
                    print(f"    Error: {attempt.exc_info[0].__name__}")
    ```
  </Accordion>

  <Accordion title="FailedConversionAttempt" icon="rotate-left">
    ### FailedConversionAttempt

    Represents a single failed attempt to convert a file. This is not an exception class, but a data class used by `FileConversionException`.

    #### Constructor Parameters

    | Parameter   | Type              | Description                                                                   |
    | ----------- | ----------------- | ----------------------------------------------------------------------------- |
    | `converter` | `Any`             | The converter instance that attempted the conversion.                         |
    | `exc_info`  | `Optional[tuple]` | Exception information tuple (type, value, traceback) from the failed attempt. |

    #### Attributes

    | Attribute   | Type              | Description                                                           |
    | ----------- | ----------------- | --------------------------------------------------------------------- |
    | `converter` | `Any`             | The converter instance that attempted the conversion.                 |
    | `exc_info`  | `Optional[tuple]` | Exception information tuple containing details about what went wrong. |

    #### Example

    ```python theme={null}
    from markitdown._exceptions import FailedConversionAttempt, FileConversionException
    import sys

    # This is typically created internally by MarkItDown
    # Example showing the structure:
    try:
        # Some conversion logic
        pass
    except Exception:
        attempt = FailedConversionAttempt(
            converter=my_converter,
            exc_info=sys.exc_info()
        )
        attempts = [attempt]
        
        # Raise FileConversionException with attempt details
        raise FileConversionException(attempts=attempts)
    ```
  </Accordion>
</AccordionGroup>

## Complete Exception Handling Example

Here's a comprehensive example showing how to handle all MarkItDown exceptions:

```python theme={null}
from markitdown import MarkItDown
from markitdown._exceptions import (
    MarkItDownException,
    MissingDependencyException,
    UnsupportedFormatException,
    FileConversionException
)

def safe_convert(file_path):
    converter = MarkItDown()
    
    try:
        result = converter.convert(file_path)
        print(f"Successfully converted {file_path}")
        return result.text_content
        
    except MissingDependencyException as e:
        print(f"Missing dependency for {file_path}")
        print(f"Error: {e}")
        print("Install the required dependencies and try again")
        return None
        
    except UnsupportedFormatException as e:
        print(f"Unsupported format for {file_path}")
        print(f"Error: {e}")
        return None
        
    except FileConversionException as e:
        print(f"Conversion failed for {file_path}")
        print(f"Error: {e}")
        
        # Detailed attempt information
        if e.attempts:
            print(f"Failed after {len(e.attempts)} attempt(s)")
            for i, attempt in enumerate(e.attempts, 1):
                converter_name = type(attempt.converter).__name__
                print(f"  Attempt {i}: {converter_name}")
        return None
        
    except MarkItDownException as e:
        # Catch any other MarkItDown exceptions
        print(f"MarkItDown error for {file_path}: {e}")
        return None
        
    except Exception as e:
        # Catch any unexpected errors
        print(f"Unexpected error for {file_path}: {e}")
        return None

# Usage
files = ["document.pdf", "data.xlsx", "presentation.pptx"]
for file in files:
    content = safe_convert(file)
    if content:
        print(f"Content preview: {content[:100]}...")
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Specific Exception Handling" icon="bullseye">
    Catch specific exceptions before the base `MarkItDownException` to handle different error scenarios appropriately.
  </Card>

  <Card title="Check Attempts" icon="list-check">
    When handling `FileConversionException`, check the `attempts` attribute for detailed diagnostic information.
  </Card>

  <Card title="Graceful Degradation" icon="shield-halved">
    Handle `MissingDependencyException` gracefully by providing clear installation instructions to users.
  </Card>

  <Card title="User Feedback" icon="message">
    Use exception messages to provide helpful feedback to users about what went wrong and how to fix it.
  </Card>
</CardGroup>
