 | |  |  |
示例JavaScript的 try-catch-finally-throw用法
- //🍎交流QQ群711841924群一,苹果内测群,528816639
- // AIWROK软件 - try-catch-finally-throw 完整演示示例
- // 全面展示JavaScript错误处理机制的各种用法
- printl("===== JavaScript try-catch-finally-throw 完整演示开始 =====");
- // =============================================================================
- // 第一部分:基础用法演示
- // =============================================================================
- printl("\n【演示1】基础try-catch用法");
- printl("----------------------------------------");
- try {
- printl("尝试执行可能出错的代码...");
- var result = 10 / 0;
- printl("计算结果: " + result);
- } catch (error) {
- printl("捕获到错误: " + error.message);
- } finally {
- printl("finally块总是会执行,无论是否发生错误");
- }
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第二部分:throw抛出错误
- // =============================================================================
- printl("\n【演示2】使用throw主动抛出错误");
- printl("----------------------------------------");
- function validateAge(age) {
- if (typeof age !== 'number') {
- throw new Error("年龄必须是数字类型");
- }
- if (age < 0 || age > 150) {
- throw new Error("年龄必须在0-150之间");
- }
- return true;
- }
- try {
- printl("验证年龄: -5");
- validateAge(-5);
- printl("✅ 验证通过");
- } catch (e) {
- printl("❌ 验证失败: " + e.message);
- }
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第三部分:自定义错误类型
- // =============================================================================
- printl("\n【演示3】创建和使用自定义错误类型");
- printl("----------------------------------------");
- // 定义自定义错误类型
- function ValidationError(message) {
- this.name = "ValidationError";
- this.message = message;
- }
- function DatabaseError(message) {
- this.name = "DatabaseError";
- this.message = message;
- }
- function NetworkError(message) {
- this.name = "NetworkError";
- this.message = message;
- }
- // 使用自定义错误
- function connectToServer(url) {
- if (!url || url === "") {
- throw new ValidationError("服务器地址不能为空");
- }
- if (url.indexOf("http") !== 0) {
- throw new NetworkError("URL格式不正确,必须以http开头");
- }
- // 模拟连接成功
- printl("连接到: " + url);
- return true;
- }
- try {
- connectToServer("");
- } catch (e) {
- printl("错误类型: " + e.name);
- printl("错误信息: " + e.message);
- }
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第四部分:嵌套try-catch
- // =============================================================================
- printl("\n【演示4】嵌套try-catch结构");
- printl("----------------------------------------");
- function processNestedData(data) {
- try {
- printl("外层try: 开始处理数据");
-
- try {
- printl(" 内层try: 验证数据格式");
- if (!data || typeof data !== 'object') {
- throw new Error("数据格式无效");
- }
- printl(" ✅ 内层验证通过");
-
- } catch (innerError) {
- printl(" ❌ 内层捕获错误: " + innerError.message);
- // 在内层处理后重新抛出
- throw new Error("数据处理失败: " + innerError.message);
- }
-
- printl("✅ 外层处理继续");
- return true;
-
- } catch (outerError) {
- printl("❌ 外层捕获错误: " + outerError.message);
- return false;
- } finally {
- printl("外层finally: 清理资源");
- }
- }
- var testData = { name: "test", value: 123 };
- processNestedData(testData);
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第五部分:多重catch捕获不同类型错误
- // =============================================================================
- printl("\n【演示5】多重catch处理不同错误类型");
- printl("----------------------------------------");
- function performOperation(operationType) {
- if (operationType === "validation") {
- throw new ValidationError("验证失败");
- } else if (operationType === "database") {
- throw new DatabaseError("数据库连接失败");
- } else if (operationType === "network") {
- throw new NetworkError("网络连接超时");
- } else {
- throw new Error("未知操作类型");
- }
- }
- // 测试不同的错误类型
- var operations = ["validation", "database", "network", "unknown"];
- for (var i = 0; i < operations.length; i++) {
- var op = operations[i];
- printl("\n执行操作: " + op);
-
- try {
- performOperation(op);
- } catch (e) {
- if (e instanceof ValidationError) {
- printl(" → 捕获验证错误: " + e.message);
- } else if (e instanceof DatabaseError) {
- printl(" → 捕获数据库错误: " + e.message);
- } else if (e instanceof NetworkError) {
- printl(" → 捕获网络错误: " + e.message);
- } else {
- printl(" → 捕获其他错误: " + e.message);
- }
- }
-
- sleep.second(2); // 2秒倒计时
- }
- // =============================================================================
- // 第六部分:finally的实际应用 - 资源清理
- // =============================================================================
- printl("\n\n【演示6】finally用于资源清理(实际应用场景)");
- printl("----------------------------------------");
- // 模拟文件操作
- var fileHandle = null;
- function simulateFileOperation(filename, shouldFail) {
- try {
- printl("打开文件: " + filename);
- fileHandle = { name: filename, isOpen: true };
- printl("✅ 文件已打开");
-
- if (shouldFail) {
- throw new Error("文件读取失败");
- }
-
- printl("读取文件内容...");
- printl("✅ 文件读取成功");
-
- return "文件内容数据";
-
- } catch (e) {
- printl("❌ 文件操作失败: " + e.message);
- return null;
-
- } finally {
- // 无论成功与否,都要关闭文件
- if (fileHandle && fileHandle.isOpen) {
- printl("关闭文件: " + fileHandle.name);
- fileHandle.isOpen = false;
- fileHandle = null;
- printl("✅ 文件已关闭(资源清理完成)");
- }
- }
- }
- // 测试成功场景
- printl("\n--- 场景1: 文件读取成功 ---");
- simulateFileOperation("config.ini", false);
- sleep.second(2); // 2秒倒计时
- // 测试失败场景
- printl("\n--- 场景2: 文件读取失败 ---");
- simulateFileOperation("data.txt", true);
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第七部分:错误传播和重新抛出
- // =============================================================================
- printl("\n【演示7】错误传播和重新抛出");
- printl("----------------------------------------");
- function layer3() {
- printl(" [第3层] 执行底层操作");
- throw new Error("底层操作失败");
- }
- function layer2() {
- try {
- printl(" [第2层] 调用第3层");
- layer3();
- } catch (e) {
- printl(" [第2层] 捕获错误: " + e.message);
- // 添加上下文信息后重新抛出
- throw new Error("第2层处理失败: " + e.message);
- }
- }
- function layer1() {
- try {
- printl("[第1层] 调用第2层");
- layer2();
- } catch (e) {
- printl("[第1层] 捕获错误: " + e.message);
- printl("[第1层] 进行最终处理");
- }
- }
- layer1();
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第八部分:条件性错误处理
- // =============================================================================
- printl("\n【演示8】条件性错误处理");
- printl("----------------------------------------");
- function processWithFallback(value, fallbackValue) {
- var result = null;
- var usedFallback = false;
-
- try {
- printl("尝试主要处理方式...");
-
- // 模拟可能失败的操作
- if (value === null || value === undefined) {
- throw new Error("值为空,无法处理");
- }
-
- // 正常处理
- result = value * 2;
- printl("✅ 主要处理成功: " + value + " * 2 = " + result);
-
- } catch (e) {
- printl("⚠️ 主要处理失败: " + e.message);
- printl("使用备用方案...");
-
- try {
- // 备用处理
- result = fallbackValue;
- usedFallback = true;
- printl("✅ 备用处理成功: " + result);
-
- } catch (fallbackError) {
- printl("❌ 备用处理也失败: " + fallbackError.message);
- result = 0;
- }
- } finally {
- printl("处理完成,使用了备用方案: " + usedFallback);
- }
-
- return { result: result, usedFallback: usedFallback };
- }
- printl("\n测试1: 正常值");
- var res1 = processWithFallback(10, 100);
- printl("结果: " + JSON.stringify(res1));
- sleep.second(2); // 2秒倒计时
- printl("\n测试2: 空值(触发备用方案)");
- var res2 = processWithFallback(null, 100);
- printl("结果: " + JSON.stringify(res2));
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第九部分:在循环中使用try-catch
- // =============================================================================
- printl("\n【演示9】在循环中使用try-catch");
- printl("----------------------------------------");
- var dataList = [
- { id: 1, value: 100 },
- { id: 2, value: null }, // 会导致错误
- { id: 3, value: 200 },
- { id: 4, value: undefined }, // 会导致错误
- { id: 5, value: 300 }
- ];
- var successCount = 0;
- var failCount = 0;
- var results = [];
- for (var i = 0; i < dataList.length; i++) {
- var item = dataList[i];
-
- try {
- printl("处理项目 " + item.id + "...");
-
- if (item.value === null || item.value === undefined) {
- throw new Error("项目 " + item.id + " 的值无效");
- }
-
- var processed = item.value * 1.1;
- results.push({ id: item.id, original: item.value, processed: processed });
- successCount++;
- printl(" ✅ 处理成功: " + item.value + " → " + processed);
-
- } catch (e) {
- failCount++;
- printl(" ❌ 处理失败: " + e.message);
- results.push({ id: item.id, error: e.message });
- }
-
- sleep.second(2); // 2秒倒计时
- }
- printl("\n循环处理统计:");
- printl(" 总数: " + dataList.length);
- printl(" 成功: " + successCount);
- printl(" 失败: " + failCount);
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第十部分:异步操作模拟中的错误处理
- // =============================================================================
- printl("\n【演示10】模拟异步操作中的错误处理");
- printl("----------------------------------------");
- function simulateAsyncOperation(taskName, shouldSucceed) {
- printl("开始异步任务: " + taskName);
-
- try {
- // 模拟异步操作的延迟
- printl(" 任务执行中...");
- sleep.second(0.5); // 0.5秒延迟
-
- if (!shouldSucceed) {
- throw new Error("任务 '" + taskName + "' 执行失败");
- }
-
- printl(" ✅ 任务完成: " + taskName);
- return { task: taskName, status: "success" };
-
- } catch (e) {
- printl(" ❌ 任务异常: " + e.message);
- return { task: taskName, status: "failed", error: e.message };
-
- } finally {
- printl(" 任务清理完成: " + taskName);
- }
- }
- // 执行多个异步任务
- var tasks = [
- { name: "下载文件", succeed: true },
- { name: "解析数据", succeed: false },
- { name: "保存结果", succeed: true },
- { name: "发送通知", succeed: true }
- ];
- var taskResults = [];
- for (var i = 0; i < tasks.length; i++) {
- var task = tasks[i];
- var result = simulateAsyncOperation(task.name, task.succeed);
- taskResults.push(result);
-
- sleep.second(2); // 2秒倒计时
- }
- printl("所有任务执行完毕,结果汇总:");
- for (var j = 0; j < taskResults.length; j++) {
- var r = taskResults[j];
- printl(" " + (j + 1) + ". " + r.task + ": " + r.status);
- }
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 第十一部分:综合实战案例 - 数据导入系统
- // =============================================================================
- printl("\n\n【演示11】综合实战案例 - 数据导入系统");
- printl("════════════════════════════════════════");
- // 模拟的数据源
- var dataSource = [
- { name: "张三", age: 25, email: "zhangsan@example.com" },
- { name: "李四", age: -5, email: "lisi@example.com" }, // 年龄无效
- { name: "", age: 30, email: "empty@example.com" }, // 姓名为空
- { name: "王五", age: 28, email: "invalid-email" }, // 邮箱格式错误
- { name: "赵六", age: 35, email: "zhaoliu@example.com" }
- ];
- // 验证函数
- function validateRecord(record) {
- if (!record.name || record.name.trim() === "") {
- throw new ValidationError("姓名不能为空");
- }
- if (typeof record.age !== 'number' || record.age < 0 || record.age > 150) {
- throw new ValidationError("年龄必须在0-150之间");
- }
- if (!record.email || record.email.indexOf('@') === -1) {
- throw new ValidationError("邮箱格式不正确");
- }
- return true;
- }
- // 导入单个记录
- function importRecord(record, index) {
- var result = {
- index: index,
- success: false,
- message: "",
- data: null
- };
-
- try {
- printl("导入记录 " + (index + 1) + ": " + record.name);
-
- // 步骤1: 验证数据
- printl(" 步骤1: 验证数据");
- validateRecord(record);
- printl(" ✅ 数据验证通过");
-
- // 步骤2: 转换数据
- printl(" 步骤2: 转换数据格式");
- var transformed = {
- id: index + 1,
- fullName: record.name.toUpperCase(),
- ageGroup: record.age < 18 ? "未成年" : (record.age < 60 ? "成年" : "老年"),
- contact: record.email
- };
- printl(" ✅ 数据转换完成");
-
- // 步骤3: 保存数据
- printl(" 步骤3: 保存到数据库");
- // 模拟保存操作
- printl(" ✅ 数据保存成功");
-
- result.success = true;
- result.message = "导入成功";
- result.data = transformed;
-
- } catch (e) {
- printl(" ❌ 导入失败: " + e.name + " - " + e.message);
- result.message = e.name + ": " + e.message;
-
- } finally {
- printl(" 记录 " + (index + 1) + " 处理完成");
- }
-
- return result;
- }
- // 批量导入
- function batchImport(dataList) {
- printl("\n开始批量数据导入");
- printl("总记录数: " + dataList.length);
- printl("----------------------------------------");
-
- var importResults = {
- total: dataList.length,
- success: 0,
- failed: 0,
- details: []
- };
-
- try {
- for (var i = 0; i < dataList.length; i++) {
- var record = dataList[i];
- var result = importRecord(record, i);
-
- importResults.details.push(result);
-
- if (result.success) {
- importResults.success++;
- } else {
- importResults.failed++;
- }
-
- sleep.second(0.3); // 0.3秒延迟
- }
-
- } catch (e) {
- printl("❌ 批量导入过程中发生严重错误: " + e.message);
-
- } finally {
- printl("========================================");
- printl("批量导入完成统计:");
- printl(" 总记录数: " + importResults.total);
- printl(" 成功: " + importResults.success);
- printl(" 失败: " + importResults.failed);
- printl(" 成功率: " + Math.round((importResults.success / importResults.total) * 100) + "%");
- printl("========================================");
- }
-
- return importResults;
- }
- // 执行批量导入
- var finalResults = batchImport(dataSource);
- // 显示详细结果
- printl("\n详细导入结果:");
- for (var k = 0; k < finalResults.details.length; k++) {
- var detail = finalResults.details[k];
- var status = detail.success ? "✅" : "❌";
- printl(" " + status + " 记录" + (detail.index + 1) + ": " + detail.message);
- }
- sleep.second(2); // 2秒倒计时
- // =============================================================================
- // 结束
- // =============================================================================
- printl("\n\n");
- printl("╔════════════════════════════════════════╗");
- printl("║ ║");
- printl("║ try-catch-finally-throw 演示完成 ║");
- printl("║ ║");
- printl("╚════════════════════════════════════════╝");
- printl("\n===== JavaScript try-catch-finally-throw 完整演示结束 =====");
复制代码
| |  | |  |
|