> ## Documentation Index
> Fetch the complete documentation index at: https://docs.plexe.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Exceptions Reference

> Comprehensive guide to exception handling in the Plexe Python library.

Plexe defines several exception types to provide clear information about errors that may occur during model building and usage. This reference documents all exception classes, their meanings, and how to handle them effectively.

## Exception Hierarchy

Plexe's exceptions inherit from a base `PlexeError` class:

```
Exception
└── PlexeError
    ├── SpecificationError
    │   ├── InsufficientSpecificationError
    │   ├── AmbiguousSpecificationError
    │   └── InvalidSchemaError
    ├── InstructionError
    ├── ConstraintError
    └── PlexeRuntimeError (also inherits from RuntimeError)
        └── CodeExecutionError
```

Note: This hierarchy reflects the current implementation and may expand in future versions.

## Base Exception

### `PlexeError`

Base exception for all Plexe-specific exceptions.

```python theme={null}
class PlexeError(Exception):
    """Base class for all Plexe-specific exceptions."""
    pass
```

## Specification Errors

### `SpecificationError`

Base class for errors related to model specification.

```python theme={null}
class SpecificationError(PlexeError):
    """Base class for errors related to model specification."""
    pass
```

### `InsufficientSpecificationError`

Raised when the natural language specification is insufficiently detailed.

```python theme={null}
class InsufficientSpecificationError(SpecificationError):
    """Raised when the natural language specification is insufficiently detailed."""
    pass
```

**Example:**

```python theme={null}
# Intent too vague
raise InsufficientSpecificationError("Intent 'analyze data' is too vague. Please provide more specific details about the task.")
```

### `AmbiguousSpecificationError`

Raised when the natural language specification is ambiguous or contradictory.

```python theme={null}
class AmbiguousSpecificationError(SpecificationError):
    """Raised when the natural language specification is ambiguous or contradictory."""
    pass
```

**Example:**

```python theme={null}
# Contradictory intent
raise AmbiguousSpecificationError("Intent contains contradictory requirements: maximize both precision and recall.")
```

### `InvalidSchemaError`

Raised when the input or output schema is invalid.

```python theme={null}
class InvalidSchemaError(SpecificationError):
    """Raised when the input or output schema is invalid."""
    pass
```

**Example:**

```python theme={null}
# Invalid schema type
raise InvalidSchemaError("Schema must be a dictionary or a Pydantic model.")

# Missing required fields
raise InvalidSchemaError("Required field 'id' missing from input schema.")
```

## Instruction Errors

### `InstructionError`

Base class for errors related to instructions provided for model building.

```python theme={null}
class InstructionError(PlexeError):
    """Base class for errors related to instructions provided for model building."""
    pass
```

**Example:**

```python theme={null}
# Invalid instruction
raise InstructionError("Unable to interpret instruction for model building.")
```

## Constraint Errors

### `ConstraintError`

Base class for errors related to constraints.

```python theme={null}
class ConstraintError(PlexeError):
    """Base class for errors related to constraints."""
    pass
```

**Example:**

```python theme={null}
# Constraint violation
raise ConstraintError("Model output violates constraint: price must be positive.")
```

## Runtime Errors

### `PlexeRuntimeError`

Base class for runtime errors during model execution or training.

```python theme={null}
class PlexeRuntimeError(PlexeError, RuntimeError):
    """Base class for runtime errors during model execution or training."""
    pass
```

### `CodeExecutionError`

Raised when code execution fails for reasons other than timeout.

```python theme={null}
class CodeExecutionError(PlexeRuntimeError):
    """Raised when code execution fails for reasons other than timeout."""
    pass
```

**Example:**

```python theme={null}
# Syntax error
raise CodeExecutionError("Syntax error in generated code: Missing colon after parameters")

# Runtime error
raise CodeExecutionError("Runtime error while executing training code: shapes (60,1) and (50,1) not aligned")
```

## Handling Exceptions

Note: The list of exception classes above represents the current implementation. In future versions, additional exception types may be added to provide more specific error information.

### Basic Exception Handling

```python theme={null}
import plexe
from plexe.exceptions import PlexeError, CodeExecutionError

try:
    model = plexe.Model(intent="Predict customer churn")
    model.build(datasets=[df])
except CodeExecutionError as e:
    print(f"Error executing generated code: {e}")
except PlexeError as e:
    print(f"Plexe error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

### Specific Exception Handling

```python theme={null}
import plexe
from plexe.exceptions import (
    SpecificationError,
    InvalidSchemaError,
    CodeExecutionError,
    PlexeRuntimeError
)

try:
    model = plexe.Model(intent="Predict customer churn")
    model.build(datasets=[df])
except InvalidSchemaError as e:
    print(f"Schema error: {e}")
    # Handle schema issues
except CodeExecutionError as e:
    print(f"Code execution error: {e}")
    # Handle generated code issues
except SpecificationError as e:
    print(f"Specification error: {e}")
    # Handle specification issues
except PlexeRuntimeError as e:
    print(f"Runtime error: {e}")
    # Handle runtime issues
```

### Prediction Error Handling

```python theme={null}
import plexe
from plexe.exceptions import PlexeError, PlexeRuntimeError

try:
    prediction = model.predict(input_data)
except PlexeRuntimeError as e:
    print(f"Runtime error during prediction: {e}")
except PlexeError as e:
    print(f"Error during prediction: {e}")
```

## Best Practices

1. **Catch Specific Exceptions:** Target the most specific exception class that makes sense for your use case.
2. **Log Detailed Information:** Include full exception details in logs for debugging.
3. **Graceful Degradation:** When possible, handle errors in a way that allows your application to continue functioning.
4. **User-Friendly Messages:** Transform technical error details into actionable user messages.
5. **Retry Strategies:** Implement retries for transient errors like LLM provider issues.

By understanding Plexe's exception hierarchy, you can write more robust code that gracefully handles potential errors in your machine learning workflows.
