1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
use Any;
use Backtrace;
use AssertUnwindSafe;
compile_error!;
/// A flexible `try_catch` macro that provides structured error and panic handling
/// with an optional `finally` block for cleanup.
///
/// # Description
/// The `try_catch!` macro allows you to define a `try` block for executing code, followed by multiple `catch`
/// blocks for handling exceptions or panics. Additionally, a `finally` block can be specified for cleanup actions.
///
/// # Syntax
/// ```text
/// try_catch! {
/// try {
/// <try_block>
/// } catch (<exception_pattern> => <exception_type>) {
/// <catch_block>
/// } catch exception (<catch_all_pattern>) {
/// <catch_all_block>
/// } catch panic (<panic_pattern>) {
/// <catch_panic_block>
/// } finally {
/// <finally_block>
/// }
/// }
/// ```
///
/// - **try block**: The primary code to execute.
/// - **catch blocks**: Handle exceptions matching specific types.
/// - **catch exception block** (optional): A generic handler for exceptions not caught by specific `catch` blocks.
/// - **catch panic block** (optional): Handle non-exception panics.
/// - **finally block** (optional): Executes unconditionally after the `try` block and any `catch` blocks.
///
/// ## Notes
/// - at least 2 blocks have to be defined you cannot have a bare try {} expression
/// - the try and catch blocks should both return the same type
/// - the finally block should return () aka "unit"
///
/// # Features
///
/// - Matches exceptions based on type.
/// - Catches generic exceptions with `catch exception`.
/// - Handles panics using `catch panic`.
/// - Ensures cleanup via an optional `finally` block.
///
/// # Usage
///
/// ## Handling specific exceptions
/// ```
/// #[derive(Debug)]
/// struct MyErrorType;
///
/// fn some_function() -> Result<i32, MyErrorType> {
/// Err(MyErrorType)
/// }
///
/// let result = rust_try_catch::try_catch! {
/// try {
/// rust_try_catch::tri!(some_function())
/// } catch (e => MyErrorType) {
/// println!("Caught MyErrorType: {e:?}");
/// -1
/// }
/// };
/// assert_eq!(result, -1);
/// ```
///
/// ## Catching all exceptions
/// ```
/// # fn another_function() {
/// # rust_try_catch::throw("Haha I failed");
/// # }
///
/// let result = rust_try_catch::try_catch! {
/// try {
/// // Code that might throw.
/// another_function();
/// 0
/// } catch exception (e) {
/// println!("Caught an exception: {:?}", e);
/// -2
/// }
/// };
/// assert_eq!(result, -2);
/// ```
///
/// ## Handling panics
/// ```
/// let result = rust_try_catch::try_catch! {
/// try {
/// // Code that might panic.
/// panic!("Unexpected error");
/// 0
/// } catch panic (e) {
/// println!("Caught a panic: {:?}", e);
/// -101
/// }
/// };
/// assert_eq!(result, -101);
/// ```
///
/// ## Using a finally block
/// ```
/// let mut cleanup = false;
/// let result = rust_try_catch::try_catch! {
/// try {
/// // Code execution.
/// 42
/// } finally {
/// cleanup = true;
/// }
/// };
/// assert_eq!(result, 42);
/// assert!(cleanup);
/// ```
///
/// ## Combining handlers
/// ```
/// # #[derive(Debug)]
/// # struct SpecificError;
/// # let risky_operation = || rust_try_catch::throw(SpecificError);
///
/// let result = rust_try_catch::try_catch! {
/// try {
/// // Code execution.
/// risky_operation();
/// 0
/// } catch (e => SpecificError) {
/// println!("Caught SpecificError: {e:?}");
/// -1
/// } catch exception (e) {
/// println!("Caught general exception: {e:?}");
/// -2
/// } catch panic (e) {
/// println!("Caught a panic: {e:?}");
/// -3
/// } finally {
/// println!("Cleanup actions here.");
/// }
/// };
/// ```
///
/// # Notes
///
/// - The `catch panic` block is only invoked for panics unrelated to exceptions handled by the macro.
/// - The `finally` block runs regardless of whether an exception or panic occurred.
/// - Unhandled exceptions or panics will propagate out of the macro.
///
/// # Examples
///
/// ## No exception or panic (doesn't compile)
/// ```compile_fail
/// let result = rust_try_catch::try_catch! {
/// try {
/// 100
/// }
/// };
/// assert_eq!(result, 100);
/// ```
///
/// ## Exception without panic
/// ```
/// # use rust_try_catch::throw;
///
/// let result = rust_try_catch::try_catch! {
/// try {
/// throw("An error occurred");
/// } catch (e => &'static str) {
/// println!("Handled error: {}", e);
/// 0
/// }
/// };
/// assert_eq!(result, 0);
/// ```
///
/// ## Panic recovery
/// ```
/// let result = rust_try_catch::try_catch! {
/// try {
/// panic!("Something went wrong!");
/// } catch panic (e) {
/// println!("Recovered from panic: {:?}", e);
/// 1
/// }
/// };
/// assert_eq!(result, 1);
/// ```
$* $? $? $?
} => ;
}
/// Unwraps a result or propagates its error as an exception.
///
/// tri! matches the given Result.
/// In case of the Ok variant, the expression has the value of the wrapped value.
/// In case of the Err variant, it retrieves the inner error, and calls throw on it.
/// Calling throw always results in a panic
///
/// for proper usage users must ensure that there is a function annotated with `rust_try_catch::throw_guard`
/// up in the call chain
!
/// # Description
/// wraps a function or closure, to prevent a thrown exception from propagating beyond them
/// and turns unhandled exceptions to a panic
///
/// # Note
/// thrown exceptions do not trigger the panic hook so if this isn't in the call chain before some code
/// throws, the process might exit abruptly due to a panic with an unspecified load
pub use ;