0
# Exception Handling
1
2
libtmux provides a comprehensive exception hierarchy for handling tmux-specific errors and edge cases. All exceptions inherit from the base `LibTmuxException` class and provide detailed error information for proper error handling and debugging.
3
4
## Capabilities
5
6
### Base Exception
7
8
Root exception class for all libtmux-specific errors.
9
10
```python { .api }
11
class LibTmuxException(Exception):
12
"""Base exception class for all libtmux errors."""
13
```
14
15
### Server and Connection Errors
16
17
Exceptions related to tmux server connection and availability.
18
19
```python { .api }
20
class TmuxCommandNotFound(LibTmuxException):
21
"""Raised when tmux binary is not found in PATH."""
22
23
class VersionTooLow(LibTmuxException):
24
"""
25
Raised when tmux version is below minimum required version.
26
27
Attributes:
28
- current_version: Detected tmux version
29
- minimum_version: Required minimum version
30
"""
31
```
32
33
### Session Management Errors
34
35
Exceptions related to session operations and lifecycle.
36
37
```python { .api }
38
class TmuxSessionExists(LibTmuxException):
39
"""Session does not exist in the server."""
40
41
class BadSessionName(LibTmuxException):
42
"""
43
Disallowed session name for tmux (empty, contains periods or colons).
44
45
Parameters:
46
- reason: Description of why session name is bad
47
- session_name: The invalid session name (optional)
48
"""
49
```
50
51
### Object Existence Errors
52
53
Exceptions for operations on non-existent tmux objects.
54
55
```python { .api }
56
class TmuxObjectDoesNotExist(ObjectDoesNotExist):
57
"""
58
The query returned multiple objects when only one was expected.
59
60
Parameters:
61
- obj_key: Object key to search for
62
- obj_id: ID of object that doesn't exist
63
- list_cmd: tmux command used for listing
64
- list_extra_args: Extra arguments for list command
65
"""
66
```
67
68
### Option Management Errors
69
70
Base and specific exceptions for tmux option operations.
71
72
```python { .api }
73
class OptionError(LibTmuxException):
74
"""Base exception for option-related errors."""
75
76
class UnknownOption(OptionError):
77
"""Option unknown to tmux show-option(s) or show-window-option(s)."""
78
79
class UnknownColorOption(UnknownOption):
80
"""
81
Unknown color option.
82
83
Automatically provides message: "Server.colors must equal 88 or 256"
84
"""
85
86
class InvalidOption(OptionError):
87
"""Option invalid to tmux, introduced in tmux v2.4."""
88
89
class AmbiguousOption(OptionError):
90
"""Option that could potentially match more than one."""
91
```
92
93
### Window Management Errors
94
95
Exceptions specific to window operations and state.
96
97
```python { .api }
98
class WindowError(LibTmuxException):
99
"""Base exception for window-related errors."""
100
101
class MultipleActiveWindows(WindowError):
102
"""
103
Multiple active windows.
104
105
Parameters:
106
- count: Number of active windows found
107
"""
108
109
class NoActiveWindow(WindowError):
110
"""No active window found."""
111
112
class NoWindowsExist(WindowError):
113
"""No windows exist for object."""
114
```
115
116
### Pane Management Errors
117
118
Exceptions specific to pane operations and state.
119
120
```python { .api }
121
class PaneError(LibTmuxException):
122
"""Base exception for pane-related errors."""
123
124
class PaneNotFound(PaneError):
125
"""
126
Pane not found.
127
128
Parameters:
129
- pane_id: ID of the missing pane (optional)
130
"""
131
```
132
133
### Resize and Adjustment Errors
134
135
Exceptions related to pane and window resizing operations.
136
137
```python { .api }
138
class AdjustmentDirectionRequiresAdjustment(LibTmuxException, ValueError):
139
"""If adjustment_direction is set, adjustment must be set."""
140
141
class WindowAdjustmentDirectionRequiresAdjustment(
142
WindowError,
143
AdjustmentDirectionRequiresAdjustment
144
):
145
"""ValueError for libtmux.Window.resize_window."""
146
147
class PaneAdjustmentDirectionRequiresAdjustment(
148
WindowError,
149
AdjustmentDirectionRequiresAdjustment
150
):
151
"""ValueError for libtmux.Pane.resize_pane."""
152
153
class RequiresDigitOrPercentage(LibTmuxException, ValueError):
154
"""
155
Requires digit (int or str digit) or a percentage.
156
157
Automatically provides message: "Requires digit (int or str digit) or a percentage."
158
"""
159
```
160
161
### Timeout and Synchronization Errors
162
163
Exceptions for timing and synchronization operations.
164
165
```python { .api }
166
class WaitTimeout(LibTmuxException):
167
"""Function timed out without meeting condition."""
168
```
169
170
### Data Processing Errors
171
172
Exceptions for internal data processing and parsing.
173
174
```python { .api }
175
class VariableUnpackingError(LibTmuxException):
176
"""
177
Error unpacking variable.
178
179
Parameters:
180
- variable: The unexpected variable that caused the error
181
"""
182
```
183
184
## Usage Examples
185
186
### Basic Exception Handling
187
188
```python
189
import libtmux
190
from libtmux.exc import TmuxSessionExists, TmuxCommandNotFound
191
192
try:
193
server = libtmux.Server()
194
session = server.new_session('my_session')
195
except TmuxCommandNotFound:
196
print("tmux is not installed or not in PATH")
197
except TmuxSessionExists as e:
198
print(f"Session '{e.session_name}' already exists")
199
# Attach to existing session instead
200
session = server.sessions.get(session_name='my_session')
201
```
202
203
### Version Checking
204
205
```python
206
import libtmux
207
from libtmux.exc import VersionTooLow
208
209
try:
210
server = libtmux.Server()
211
# Some operation requiring newer tmux version
212
except VersionTooLow as e:
213
print(f"tmux version {e.current_version} is too old")
214
print(f"Minimum required version: {e.minimum_version}")
215
```
216
217
### Option Management Error Handling
218
219
```python
220
import libtmux
221
from libtmux.exc import UnknownOption, InvalidOption, AmbiguousOption
222
223
server = libtmux.Server()
224
session = server.new_session('test')
225
226
try:
227
session.set_option('invalid-option', 'value')
228
except UnknownOption as e:
229
print(f"Unknown option: {e.option}")
230
except InvalidOption as e:
231
print(f"Invalid value '{e.value}' for option '{e.option}': {e.reason}")
232
except AmbiguousOption as e:
233
print(f"Ambiguous option '{e.option}' matches: {e.matches}")
234
```
235
236
### Object Existence Checking
237
238
```python
239
import libtmux
240
from libtmux.exc import TmuxObjectDoesNotExist
241
242
server = libtmux.Server()
243
244
try:
245
# Try to get non-existent session
246
session = server.sessions.get(session_name='nonexistent')
247
except TmuxObjectDoesNotExist as e:
248
print(f"Object {e.object_type} '{e.object_id}' does not exist")
249
# Create session instead
250
session = server.new_session('nonexistent')
251
```
252
253
### Window and Pane Error Handling
254
255
```python
256
import libtmux
257
from libtmux.exc import NoActiveWindow, PaneNotFound, MultipleActiveWindows
258
259
server = libtmux.Server()
260
session = server.new_session('window_test')
261
262
try:
263
active_window = session.active_window
264
except NoActiveWindow:
265
print("No active window in session")
266
# Create a window
267
window = session.new_window('main')
268
except MultipleActiveWindows as e:
269
print(f"Multiple active windows found: {e.windows}")
270
# Select first one
271
window = session.windows[0]
272
window.select()
273
274
try:
275
pane = window.panes.get(pane_id='%999')
276
except PaneNotFound as e:
277
print(f"Pane {e.pane_id} not found")
278
```
279
280
### Resize Error Handling
281
282
```python
283
import libtmux
284
from libtmux.exc import (
285
PaneAdjustmentDirectionRequiresAdjustment,
286
RequiresDigitOrPercentage
287
)
288
289
server = libtmux.Server()
290
session = server.new_session('resize_test')
291
window = session.new_window('main')
292
pane = window.active_pane
293
294
try:
295
pane.resize('right') # Missing adjustment amount
296
except PaneAdjustmentDirectionRequiresAdjustment:
297
print("Resize direction requires adjustment amount")
298
pane.resize('right', 10)
299
300
try:
301
pane.set_width('invalid') # Invalid size format
302
except RequiresDigitOrPercentage as e:
303
print(f"Invalid size value: {e.value}")
304
pane.set_width(80) # Use valid number
305
```
306
307
### Comprehensive Error Handling
308
309
```python
310
import libtmux
311
from libtmux.exc import LibTmuxException
312
313
def safe_tmux_operation():
314
try:
315
server = libtmux.Server()
316
session = server.new_session('safe_session')
317
window = session.new_window('main')
318
pane = window.split_window()
319
320
pane.send_keys('echo "Success"')
321
output = pane.capture_pane()
322
return output
323
324
except LibTmuxException as e:
325
print(f"tmux operation failed: {e}")
326
return None
327
except Exception as e:
328
print(f"Unexpected error: {e}")
329
return None
330
331
result = safe_tmux_operation()
332
if result:
333
print("Operation succeeded:", result)
334
else:
335
print("Operation failed")
336
```