Repository navigation
Expand file tree
/
Copy path06_exceptions.candle
More file actions
441 lines (351 loc) · 9.9 KB
/
Copy path06_exceptions.candle
File metadata and controls
441 lines (351 loc) · 9.9 KB
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/// Candle 语言异常处理模板
/// 展示 try-catch-finally、throw、自定义异常等特性
// ==================== 基础异常处理 ====================
void basicExceptionHandling() {
print("=== 基础异常处理 ===\n");
try {
print("尝试执行可能出错的代码\n");
int result = 10 / 0; // 除零错误
print(result);
} catch (Exception e) {
print("捕获到异常\n");
}
print("程序继续执行\n\n");
}
// ==================== Finally 块 ====================
void finallyBlockExample() {
print("=== Finally 块示例 ===\n");
try {
print("执行主逻辑\n");
int result = 10 / 2;
print("结果: ");
print(result);
print("\n");
} catch (Exception e) {
print("处理异常\n");
} finally {
print("Finally 块总是执行(清理资源)\n");
}
print("\n");
}
// ==================== 抛出异常 ====================
void throwException(int value) {
if (value < 0) {
throw Exception("值不能为负数");
}
print("值是有效的: ");
print(value);
print("\n");
}
void throwExampleUsage() {
print("=== 抛出异常示例 ===\n");
try {
throwException(10); // 正常
throwException(-5); // 抛出异常
} catch (Exception e) {
print("捕获异常\n");
}
print("\n");
}
// ==================== 自定义异常类 ====================
/// 自定义异常:值范围错误
class ValueError inherit Exception {
String message;
ValueError(String message) {
this.message = message;
}
String toString() {
return "ValueError: " + this.message;
}
}
/// 自定义异常:空值错误
class NullError inherit Exception {
String message;
NullError(String message) {
this.message = message;
}
String toString() {
return "NullError: " + this.message;
}
}
/// 自定义异常:索引越界
class IndexOutOfBoundsError inherit Exception {
int index;
int size;
IndexOutOfBoundsError(int index, int size) {
this.index = index;
this.size = size;
}
String toString() {
return "IndexOutOfBoundsError: index " + this.index + " is out of bounds (size: " + this.size + ")";
}
}
// ==================== 多个 Catch 块 ====================
void multipleCatchBlocks() {
print("=== 多个 Catch 块 ===\n");
try {
throw ValueError("自定义值错误");
} catch (ValueError e) {
print("捕获 ValueError\n");
} catch (NullError e) {
print("捕获 NullError\n");
} catch (Exception e) {
print("捕获通用异常\n");
}
print("\n");
}
// ==================== 异常传播 ====================
void innerFunction() {
print("innerFunction: 抛出异常\n");
throw Exception("来自内部函数的异常");
}
void middleFunction() {
print("middleFunction: 调用 innerFunction\n");
innerFunction(); // 异常会向上传播
}
void outerFunction() {
print("=== 异常传播 ===\n");
try {
middleFunction();
} catch (Exception e) {
print("outerFunction: 捕获了来自深层调用的异常\n");
}
print("\n");
}
// ==================== 重新抛出异常 ====================
void rethrowException() {
print("=== 重新抛出异常 ===\n");
try {
try {
throw Exception("原始异常");
} catch (Exception e) {
print("第一层捕获异常\n");
throw e; // 重新抛出
}
} catch (Exception e) {
print("第二层捕获异常\n");
}
print("\n");
}
// ==================== 带异常的函数示例 ====================
/// 安全除法:处理除零异常
double safeDivide(double a, double b) {
try {
if (b == 0.0) {
throw ValueError("除数不能为零");
}
return a / b;
} catch (ValueError e) {
print("除法错误,返回 0.0\n");
return 0.0;
}
}
/// 安全访问列表元素
int safeGetListElement(List<int> list, int index) {
try {
if (index < 0 || index >= list.length()) {
throw IndexOutOfBoundsError(index, list.length());
}
return list[index];
} catch (IndexOutOfBoundsError e) {
print("索引越界,返回默认值 0\n");
return 0;
}
}
// ==================== 资源清理模式 ====================
class FileHandle {
String path;
bool isOpen;
FileHandle(String path) {
this.path = path;
this.isOpen = false;
}
void open() {
print("打开文件: ");
print(this.path);
print("\n");
this.isOpen = true;
}
void write(String content) {
if (!this.isOpen) {
throw Exception("文件未打开");
}
print("写入内容: ");
print(content);
print("\n");
}
void close() {
print("关闭文件: ");
print(this.path);
print("\n");
this.isOpen = false;
}
}
void resourceCleanupPattern() {
print("=== 资源清理模式 ===\n");
FileHandle file = FileHandle("data.txt");
try {
file.open();
file.write("Hello, World!");
// 可能抛出异常的操作
} catch (Exception e) {
print("文件操作异常\n");
} finally {
// 确保资源被释放
if (file.isOpen) {
file.close();
}
}
print("\n");
}
// ==================== 异常处理最佳实践 ====================
class Calculator {
/// 带验证的加法
int add(int a, int b) {
if (a > 1000000 || b > 1000000) {
throw ValueError("数值过大");
}
return a + b;
}
/// 带验证的除法
double divide(int a, int b) {
if (b == 0) {
throw ValueError("除数不能为零");
}
return a / b;
}
/// 带验证的开方
double squareRoot(double x) {
if (x < 0.0) {
throw ValueError("不能对负数开方");
}
return Math.sqrt(x);
}
}
void bestPracticesExample() {
print("=== 异常处理最佳实践 ===\n");
Calculator calc = Calculator();
// 1. 预期的异常应该被处理
try {
double result = calc.divide(10, 0);
print(result);
} catch (ValueError e) {
print("预期的异常:除数为零\n");
}
// 2. 使用 finally 清理资源
FileHandle file = FileHandle("output.txt");
try {
file.open();
file.write("Data");
} finally {
if (file.isOpen) {
file.close();
}
}
// 3. 不要捕获过于宽泛的异常
try {
calc.squareRoot(-1.0);
} catch (ValueError e) {
// 只捕获特定异常
print("预期的异常:负数开方\n");
}
print("\n");
}
// ==================== 异常链(如果支持)====================
void exceptionChaining() {
print("=== 异常链 ===\n");
try {
try {
throw Exception("原始错误");
} catch (Exception inner) {
// 包装异常,保留原始错误信息
throw Exception("包装错误(由原始错误引起)");
}
} catch (Exception outer) {
print("捕获包装后的异常\n");
}
print("\n");
}
// ==================== 综合示例 ====================
int main() {
print("=== Candle 异常处理演示 ===\n\n");
// 1. 基础异常处理
basicExceptionHandling();
// 2. Finally 块
finallyBlockExample();
// 3. 抛出异常
throwExampleUsage();
// 4. 多个 Catch 块
multipleCatchBlocks();
// 5. 异常传播
outerFunction();
// 6. 重新抛出异常
rethrowException();
// 7. 安全函数示例
print("=== 安全函数示例 ===\n");
double divResult = safeDivide(10.0, 2.0);
print("除法结果: ");
print(divResult);
print("\n");
double badDiv = safeDivide(10.0, 0.0);
print("错误除法结果: ");
print(badDiv);
print("\n\n");
// 8. 列表安全访问
print("=== 列表安全访问 ===\n");
List<int> numbers = List<int>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
int value1 = safeGetListElement(numbers, 1);
print("索引 1: ");
print(value1);
print("\n");
int value2 = safeGetListElement(numbers, 10);
print("索引 10: ");
print(value2);
print("\n\n");
// 9. 资源清理模式
resourceCleanupPattern();
// 10. 最佳实践
bestPracticesExample();
// 11. 异常链
exceptionChaining();
print("=== 异常处理演示完成 ===\n");
return 0;
}
// ==================== 异常处理总结 ====================
/*
异常处理最佳实践:
1. 何时使用异常
- 用于处理异常情况,而非正常流程控制
- 预期的错误(如用户输入错误)
- 资源访问失败(文件、网络、数据库)
- 违反前置条件或不变量
2. 异常类型层次
Exception (基类)
├── ValueError (值错误)
├── NullError (空值错误)
├── IndexOutOfBoundsError (索引越界)
├── IOException (I/O 错误)
└── RuntimeError (运行时错误)
3. Try-Catch-Finally 结构
- try: 包含可能抛出异常的代码
- catch: 捕获并处理特定异常
- finally: 无论是否异常都执行(清理资源)
4. 异常处理原则
- 只捕获能处理的异常
- 不要捕获过于宽泛的异常
- 使用 finally 确保资源释放
- 提供有意义的错误信息
- 考虑异常传播路径
5. 避免的反模式
- 空的 catch 块(吞掉异常)
- 捕获 Exception 后什么都不做
- 使用异常控制正常流程
- 过度使用异常(性能开销)
6. 资源管理
- 文件、网络连接等资源必须在 finally 中关闭
- 考虑使用 try-with-resources 模式(如果支持)
- 确保异常情况下也能释放资源
*/