|
| 1 | +package com.cyrus.example.shell |
| 2 | + |
| 3 | +class TryItemExample { |
| 4 | + |
| 5 | + // ✅ 0. 没有 try-catch(不会生成 TryItem) |
| 6 | + fun noTryCatch(): Int { |
| 7 | + val a = 1 |
| 8 | + val b = 2 |
| 9 | + return a + b |
| 10 | + } |
| 11 | + |
| 12 | + // ✅ 1. 简单 try-catch(一个 TryItem) |
| 13 | + fun simpleTryCatch(): String { |
| 14 | + return try { |
| 15 | + val x = 10 / 2 |
| 16 | + "Result: $x" |
| 17 | + } catch (e: Exception) { |
| 18 | + "Caught Exception" |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + // ✅ 2. 多个 catch 分支(一个 TryItem,多个 handler entry) |
| 23 | + fun multiCatch(input: String?): Int { |
| 24 | + return try { |
| 25 | + input!!.length |
| 26 | + } catch (e: NullPointerException) { |
| 27 | + -1 |
| 28 | + } catch (e: Exception) { |
| 29 | + -2 |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // ✅ 3. try-catch-finally(一个 TryItem + finally handler) |
| 34 | + fun tryCatchFinally(): Int { |
| 35 | + return try { |
| 36 | + 1 / 0 |
| 37 | + } catch (e: ArithmeticException) { |
| 38 | + -100 |
| 39 | + } finally { |
| 40 | + println("finally block executed") |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // ✅ 4. 嵌套 try-catch(两个 TryItem,嵌套结构) |
| 45 | + fun nestedTryCatch(): String { |
| 46 | + return try { |
| 47 | + try { |
| 48 | + val data = "123".toInt() |
| 49 | + "Parsed: $data" |
| 50 | + } catch (e: NumberFormatException) { |
| 51 | + "Inner Catch" |
| 52 | + } |
| 53 | + } catch (e: Exception) { |
| 54 | + "Outer Catch" |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + // ✅ 5. 只有 finally,无 catch(一个 TryItem,无 handler entry) |
| 59 | + fun onlyFinally(): Int { |
| 60 | + try { |
| 61 | + val x = 1 + 1 |
| 62 | + } finally { |
| 63 | + println("executing finally without catch") |
| 64 | + } |
| 65 | + return 0 |
| 66 | + } |
| 67 | + |
| 68 | + // ✅ 6. 多个独立 try 块(多个 TryItem,非嵌套) |
| 69 | + fun multipleTryBlocks(): Int { |
| 70 | + try { |
| 71 | + val x = 10 / (1 - 1) // 故意制造除零异常,确保不会被优化 |
| 72 | + } catch (e: Exception) { |
| 73 | + println("First catch") |
| 74 | + } |
| 75 | + |
| 76 | + try { |
| 77 | + val b = "abc".toInt() // 会抛出 NumberFormatException |
| 78 | + } catch (e: NumberFormatException) { |
| 79 | + println("Second catch") |
| 80 | + } |
| 81 | + |
| 82 | + return 0 |
| 83 | + } |
| 84 | +} |
0 commit comments