自动发帖软件

标题: 示例JavaScript的 try-catch-finally-throw用法 [打印本页]

作者: 发帖软件    时间: 2 小时前
标题: 示例JavaScript的 try-catch-finally-throw用法

示例JavaScript的 try-catch-finally-throw用法
示例JavaScript的 try-catch-finally-throw用法 群发软件发帖工具
示例JavaScript的 try-catch-finally-throw用法 群发软件发帖工具



  1. //🍎交流QQ群711841924群一,苹果内测群,528816639
  2. // AIWROK软件 - try-catch-finally-throw 完整演示示例
  3. // 全面展示JavaScript错误处理机制的各种用法

  4. printl("===== JavaScript try-catch-finally-throw 完整演示开始 =====");

  5. // =============================================================================
  6. // 第一部分:基础用法演示
  7. // =============================================================================

  8. printl("\n【演示1】基础try-catch用法");
  9. printl("----------------------------------------");

  10. try {
  11.     printl("尝试执行可能出错的代码...");
  12.     var result = 10 / 0;
  13.     printl("计算结果: " + result);
  14. } catch (error) {
  15.     printl("捕获到错误: " + error.message);
  16. } finally {
  17.     printl("finally块总是会执行,无论是否发生错误");
  18. }

  19. sleep.second(2);  // 2秒倒计时

  20. // =============================================================================
  21. // 第二部分:throw抛出错误
  22. // =============================================================================

  23. printl("\n【演示2】使用throw主动抛出错误");
  24. printl("----------------------------------------");

  25. function validateAge(age) {
  26.     if (typeof age !== 'number') {
  27.         throw new Error("年龄必须是数字类型");
  28.     }
  29.     if (age < 0 || age > 150) {
  30.         throw new Error("年龄必须在0-150之间");
  31.     }
  32.     return true;
  33. }

  34. try {
  35.     printl("验证年龄: -5");
  36.     validateAge(-5);
  37.     printl("✅ 验证通过");
  38. } catch (e) {
  39.     printl("❌ 验证失败: " + e.message);
  40. }

  41. sleep.second(2);  // 2秒倒计时

  42. // =============================================================================
  43. // 第三部分:自定义错误类型
  44. // =============================================================================

  45. printl("\n【演示3】创建和使用自定义错误类型");
  46. printl("----------------------------------------");

  47. // 定义自定义错误类型
  48. function ValidationError(message) {
  49.     this.name = "ValidationError";
  50.     this.message = message;
  51. }

  52. function DatabaseError(message) {
  53.     this.name = "DatabaseError";
  54.     this.message = message;
  55. }

  56. function NetworkError(message) {
  57.     this.name = "NetworkError";
  58.     this.message = message;
  59. }

  60. // 使用自定义错误
  61. function connectToServer(url) {
  62.     if (!url || url === "") {
  63.         throw new ValidationError("服务器地址不能为空");
  64.     }
  65.     if (url.indexOf("http") !== 0) {
  66.         throw new NetworkError("URL格式不正确,必须以http开头");
  67.     }
  68.     // 模拟连接成功
  69.     printl("连接到: " + url);
  70.     return true;
  71. }

  72. try {
  73.     connectToServer("");
  74. } catch (e) {
  75.     printl("错误类型: " + e.name);
  76.     printl("错误信息: " + e.message);
  77. }

  78. sleep.second(2);  // 2秒倒计时

  79. // =============================================================================
  80. // 第四部分:嵌套try-catch
  81. // =============================================================================

  82. printl("\n【演示4】嵌套try-catch结构");
  83. printl("----------------------------------------");

  84. function processNestedData(data) {
  85.     try {
  86.         printl("外层try: 开始处理数据");
  87.         
  88.         try {
  89.             printl("  内层try: 验证数据格式");
  90.             if (!data || typeof data !== 'object') {
  91.                 throw new Error("数据格式无效");
  92.             }
  93.             printl("  ✅ 内层验证通过");
  94.             
  95.         } catch (innerError) {
  96.             printl("  ❌ 内层捕获错误: " + innerError.message);
  97.             // 在内层处理后重新抛出
  98.             throw new Error("数据处理失败: " + innerError.message);
  99.         }
  100.         
  101.         printl("✅ 外层处理继续");
  102.         return true;
  103.         
  104.     } catch (outerError) {
  105.         printl("❌ 外层捕获错误: " + outerError.message);
  106.         return false;
  107.     } finally {
  108.         printl("外层finally: 清理资源");
  109.     }
  110. }

  111. var testData = { name: "test", value: 123 };
  112. processNestedData(testData);

  113. sleep.second(2);  // 2秒倒计时

  114. // =============================================================================
  115. // 第五部分:多重catch捕获不同类型错误
  116. // =============================================================================

  117. printl("\n【演示5】多重catch处理不同错误类型");
  118. printl("----------------------------------------");

  119. function performOperation(operationType) {
  120.     if (operationType === "validation") {
  121.         throw new ValidationError("验证失败");
  122.     } else if (operationType === "database") {
  123.         throw new DatabaseError("数据库连接失败");
  124.     } else if (operationType === "network") {
  125.         throw new NetworkError("网络连接超时");
  126.     } else {
  127.         throw new Error("未知操作类型");
  128.     }
  129. }

  130. // 测试不同的错误类型
  131. var operations = ["validation", "database", "network", "unknown"];

  132. for (var i = 0; i < operations.length; i++) {
  133.     var op = operations[i];
  134.     printl("\n执行操作: " + op);
  135.    
  136.     try {
  137.         performOperation(op);
  138.     } catch (e) {
  139.         if (e instanceof ValidationError) {
  140.             printl("  → 捕获验证错误: " + e.message);
  141.         } else if (e instanceof DatabaseError) {
  142.             printl("  → 捕获数据库错误: " + e.message);
  143.         } else if (e instanceof NetworkError) {
  144.             printl("  → 捕获网络错误: " + e.message);
  145.         } else {
  146.             printl("  → 捕获其他错误: " + e.message);
  147.         }
  148.     }
  149.    
  150.     sleep.second(2);  // 2秒倒计时
  151. }

  152. // =============================================================================
  153. // 第六部分:finally的实际应用 - 资源清理
  154. // =============================================================================

  155. printl("\n\n【演示6】finally用于资源清理(实际应用场景)");
  156. printl("----------------------------------------");

  157. // 模拟文件操作
  158. var fileHandle = null;

  159. function simulateFileOperation(filename, shouldFail) {
  160.     try {
  161.         printl("打开文件: " + filename);
  162.         fileHandle = { name: filename, isOpen: true };
  163.         printl("✅ 文件已打开");
  164.         
  165.         if (shouldFail) {
  166.             throw new Error("文件读取失败");
  167.         }
  168.         
  169.         printl("读取文件内容...");
  170.         printl("✅ 文件读取成功");
  171.         
  172.         return "文件内容数据";
  173.         
  174.     } catch (e) {
  175.         printl("❌ 文件操作失败: " + e.message);
  176.         return null;
  177.         
  178.     } finally {
  179.         // 无论成功与否,都要关闭文件
  180.         if (fileHandle && fileHandle.isOpen) {
  181.             printl("关闭文件: " + fileHandle.name);
  182.             fileHandle.isOpen = false;
  183.             fileHandle = null;
  184.             printl("✅ 文件已关闭(资源清理完成)");
  185.         }
  186.     }
  187. }

  188. // 测试成功场景
  189. printl("\n--- 场景1: 文件读取成功 ---");
  190. simulateFileOperation("config.ini", false);

  191. sleep.second(2);  // 2秒倒计时

  192. // 测试失败场景
  193. printl("\n--- 场景2: 文件读取失败 ---");
  194. simulateFileOperation("data.txt", true);

  195. sleep.second(2);  // 2秒倒计时

  196. // =============================================================================
  197. // 第七部分:错误传播和重新抛出
  198. // =============================================================================

  199. printl("\n【演示7】错误传播和重新抛出");
  200. printl("----------------------------------------");

  201. function layer3() {
  202.     printl("  [第3层] 执行底层操作");
  203.     throw new Error("底层操作失败");
  204. }

  205. function layer2() {
  206.     try {
  207.         printl("  [第2层] 调用第3层");
  208.         layer3();
  209.     } catch (e) {
  210.         printl("  [第2层] 捕获错误: " + e.message);
  211.         // 添加上下文信息后重新抛出
  212.         throw new Error("第2层处理失败: " + e.message);
  213.     }
  214. }

  215. function layer1() {
  216.     try {
  217.         printl("[第1层] 调用第2层");
  218.         layer2();
  219.     } catch (e) {
  220.         printl("[第1层] 捕获错误: " + e.message);
  221.         printl("[第1层] 进行最终处理");
  222.     }
  223. }

  224. layer1();

  225. sleep.second(2);  // 2秒倒计时

  226. // =============================================================================
  227. // 第八部分:条件性错误处理
  228. // =============================================================================

  229. printl("\n【演示8】条件性错误处理");
  230. printl("----------------------------------------");

  231. function processWithFallback(value, fallbackValue) {
  232.     var result = null;
  233.     var usedFallback = false;
  234.    
  235.     try {
  236.         printl("尝试主要处理方式...");
  237.         
  238.         // 模拟可能失败的操作
  239.         if (value === null || value === undefined) {
  240.             throw new Error("值为空,无法处理");
  241.         }
  242.         
  243.         // 正常处理
  244.         result = value * 2;
  245.         printl("✅ 主要处理成功: " + value + " * 2 = " + result);
  246.         
  247.     } catch (e) {
  248.         printl("⚠️ 主要处理失败: " + e.message);
  249.         printl("使用备用方案...");
  250.         
  251.         try {
  252.             // 备用处理
  253.             result = fallbackValue;
  254.             usedFallback = true;
  255.             printl("✅ 备用处理成功: " + result);
  256.             
  257.         } catch (fallbackError) {
  258.             printl("❌ 备用处理也失败: " + fallbackError.message);
  259.             result = 0;
  260.         }
  261.     } finally {
  262.         printl("处理完成,使用了备用方案: " + usedFallback);
  263.     }
  264.    
  265.     return { result: result, usedFallback: usedFallback };
  266. }

  267. printl("\n测试1: 正常值");
  268. var res1 = processWithFallback(10, 100);
  269. printl("结果: " + JSON.stringify(res1));

  270. sleep.second(2);  // 2秒倒计时

  271. printl("\n测试2: 空值(触发备用方案)");
  272. var res2 = processWithFallback(null, 100);
  273. printl("结果: " + JSON.stringify(res2));

  274. sleep.second(2);  // 2秒倒计时

  275. // =============================================================================
  276. // 第九部分:在循环中使用try-catch
  277. // =============================================================================

  278. printl("\n【演示9】在循环中使用try-catch");
  279. printl("----------------------------------------");

  280. var dataList = [
  281.     { id: 1, value: 100 },
  282.     { id: 2, value: null },  // 会导致错误
  283.     { id: 3, value: 200 },
  284.     { id: 4, value: undefined },  // 会导致错误
  285.     { id: 5, value: 300 }
  286. ];

  287. var successCount = 0;
  288. var failCount = 0;
  289. var results = [];

  290. for (var i = 0; i < dataList.length; i++) {
  291.     var item = dataList[i];
  292.    
  293.     try {
  294.         printl("处理项目 " + item.id + "...");
  295.         
  296.         if (item.value === null || item.value === undefined) {
  297.             throw new Error("项目 " + item.id + " 的值无效");
  298.         }
  299.         
  300.         var processed = item.value * 1.1;
  301.         results.push({ id: item.id, original: item.value, processed: processed });
  302.         successCount++;
  303.         printl("  ✅ 处理成功: " + item.value + " → " + processed);
  304.         
  305.     } catch (e) {
  306.         failCount++;
  307.         printl("  ❌ 处理失败: " + e.message);
  308.         results.push({ id: item.id, error: e.message });
  309.     }
  310.    
  311.     sleep.second(2);  // 2秒倒计时
  312. }

  313. printl("\n循环处理统计:");
  314. printl("  总数: " + dataList.length);
  315. printl("  成功: " + successCount);
  316. printl("  失败: " + failCount);

  317. sleep.second(2);  // 2秒倒计时

  318. // =============================================================================
  319. // 第十部分:异步操作模拟中的错误处理
  320. // =============================================================================

  321. printl("\n【演示10】模拟异步操作中的错误处理");
  322. printl("----------------------------------------");

  323. function simulateAsyncOperation(taskName, shouldSucceed) {
  324.     printl("开始异步任务: " + taskName);
  325.    
  326.     try {
  327.         // 模拟异步操作的延迟
  328.         printl("  任务执行中...");
  329.         sleep.second(0.5);  // 0.5秒延迟
  330.         
  331.         if (!shouldSucceed) {
  332.             throw new Error("任务 '" + taskName + "' 执行失败");
  333.         }
  334.         
  335.         printl("  ✅ 任务完成: " + taskName);
  336.         return { task: taskName, status: "success" };
  337.         
  338.     } catch (e) {
  339.         printl("  ❌ 任务异常: " + e.message);
  340.         return { task: taskName, status: "failed", error: e.message };
  341.         
  342.     } finally {
  343.         printl("  任务清理完成: " + taskName);
  344.     }
  345. }

  346. // 执行多个异步任务
  347. var tasks = [
  348.     { name: "下载文件", succeed: true },
  349.     { name: "解析数据", succeed: false },
  350.     { name: "保存结果", succeed: true },
  351.     { name: "发送通知", succeed: true }
  352. ];

  353. var taskResults = [];

  354. for (var i = 0; i < tasks.length; i++) {
  355.     var task = tasks[i];
  356.     var result = simulateAsyncOperation(task.name, task.succeed);
  357.     taskResults.push(result);
  358.    
  359.     sleep.second(2);  // 2秒倒计时
  360. }

  361. printl("所有任务执行完毕,结果汇总:");
  362. for (var j = 0; j < taskResults.length; j++) {
  363.     var r = taskResults[j];
  364.     printl("  " + (j + 1) + ". " + r.task + ": " + r.status);
  365. }

  366. sleep.second(2);  // 2秒倒计时

  367. // =============================================================================
  368. // 第十一部分:综合实战案例 - 数据导入系统
  369. // =============================================================================

  370. printl("\n\n【演示11】综合实战案例 - 数据导入系统");
  371. printl("════════════════════════════════════════");

  372. // 模拟的数据源
  373. var dataSource = [
  374.     { name: "张三", age: 25, email: "zhangsan@example.com" },
  375.     { name: "李四", age: -5, email: "lisi@example.com" },  // 年龄无效
  376.     { name: "", age: 30, email: "empty@example.com" },  // 姓名为空
  377.     { name: "王五", age: 28, email: "invalid-email" },  // 邮箱格式错误
  378.     { name: "赵六", age: 35, email: "zhaoliu@example.com" }
  379. ];

  380. // 验证函数
  381. function validateRecord(record) {
  382.     if (!record.name || record.name.trim() === "") {
  383.         throw new ValidationError("姓名不能为空");
  384.     }
  385.     if (typeof record.age !== 'number' || record.age < 0 || record.age > 150) {
  386.         throw new ValidationError("年龄必须在0-150之间");
  387.     }
  388.     if (!record.email || record.email.indexOf('@') === -1) {
  389.         throw new ValidationError("邮箱格式不正确");
  390.     }
  391.     return true;
  392. }

  393. // 导入单个记录
  394. function importRecord(record, index) {
  395.     var result = {
  396.         index: index,
  397.         success: false,
  398.         message: "",
  399.         data: null
  400.     };
  401.    
  402.     try {
  403.         printl("导入记录 " + (index + 1) + ": " + record.name);
  404.         
  405.         // 步骤1: 验证数据
  406.         printl("  步骤1: 验证数据");
  407.         validateRecord(record);
  408.         printl("  ✅ 数据验证通过");
  409.         
  410.         // 步骤2: 转换数据
  411.         printl("  步骤2: 转换数据格式");
  412.         var transformed = {
  413.             id: index + 1,
  414.             fullName: record.name.toUpperCase(),
  415.             ageGroup: record.age < 18 ? "未成年" : (record.age < 60 ? "成年" : "老年"),
  416.             contact: record.email
  417.         };
  418.         printl("  ✅ 数据转换完成");
  419.         
  420.         // 步骤3: 保存数据
  421.         printl("  步骤3: 保存到数据库");
  422.         // 模拟保存操作
  423.         printl("  ✅ 数据保存成功");
  424.         
  425.         result.success = true;
  426.         result.message = "导入成功";
  427.         result.data = transformed;
  428.         
  429.     } catch (e) {
  430.         printl("  ❌ 导入失败: " + e.name + " - " + e.message);
  431.         result.message = e.name + ": " + e.message;
  432.         
  433.     } finally {
  434.         printl("  记录 " + (index + 1) + " 处理完成");
  435.     }
  436.    
  437.     return result;
  438. }

  439. // 批量导入
  440. function batchImport(dataList) {
  441.     printl("\n开始批量数据导入");
  442.     printl("总记录数: " + dataList.length);
  443.     printl("----------------------------------------");
  444.    
  445.     var importResults = {
  446.         total: dataList.length,
  447.         success: 0,
  448.         failed: 0,
  449.         details: []
  450.     };
  451.    
  452.     try {
  453.         for (var i = 0; i < dataList.length; i++) {
  454.             var record = dataList[i];
  455.             var result = importRecord(record, i);
  456.             
  457.             importResults.details.push(result);
  458.             
  459.             if (result.success) {
  460.                 importResults.success++;
  461.             } else {
  462.                 importResults.failed++;
  463.             }
  464.             
  465.             sleep.second(0.3);  // 0.3秒延迟
  466.         }
  467.         
  468.     } catch (e) {
  469.         printl("❌ 批量导入过程中发生严重错误: " + e.message);
  470.         
  471.     } finally {
  472.         printl("========================================");
  473.         printl("批量导入完成统计:");
  474.         printl("  总记录数: " + importResults.total);
  475.         printl("  成功: " + importResults.success);
  476.         printl("  失败: " + importResults.failed);
  477.         printl("  成功率: " + Math.round((importResults.success / importResults.total) * 100) + "%");
  478.         printl("========================================");
  479.     }
  480.    
  481.     return importResults;
  482. }

  483. // 执行批量导入
  484. var finalResults = batchImport(dataSource);

  485. // 显示详细结果
  486. printl("\n详细导入结果:");
  487. for (var k = 0; k < finalResults.details.length; k++) {
  488.     var detail = finalResults.details[k];
  489.     var status = detail.success ? "✅" : "❌";
  490.     printl("  " + status + " 记录" + (detail.index + 1) + ": " + detail.message);
  491. }

  492. sleep.second(2);  // 2秒倒计时

  493. // =============================================================================
  494. // 结束
  495. // =============================================================================

  496. printl("\n\n");
  497. printl("╔════════════════════════════════════════╗");
  498. printl("║                                        ║");
  499. printl("║   try-catch-finally-throw 演示完成    ║");
  500. printl("║                                        ║");
  501. printl("╚════════════════════════════════════════╝");

  502. printl("\n===== JavaScript try-catch-finally-throw 完整演示结束 =====");
复制代码







欢迎光临 自动发帖软件 (http://www.fatiegongju.com/) Powered by Discuz! X3.2