异常处理:
1 // 2 // ViewController5.swift 3 // SwiftBasicDemo 4 // 5 // Created by 思 彭 on 16/11/16. 6 // Copyright ? 2016年 思 彭. All rights reserved. 7 8 // 错误处理 9 10 import UIKit 11 12 class ViewController5: UIViewController { 13 14 override func viewDidLoad() { 15 super.viewDidLoad() 16 self.title = "错误处理" 17 18 // 1.函数内的 throws异常处理 19 func send(job: Int, toPrinter printrName: String) throws ->String { 20 if printrName == "Never Has Toner" { 21 throw PrintError.noToner 22 } 23 return "Job sent" 24 } 25 26 // 2.do...catch处理异常 输出: Job sent 27 do { 28 29 let printerresponse = try send(job: 1040, toPrinter: "Bi Sheng") 30 print(printerresponse) 31 }catch { 32 print("error = \(error)") 33 } 34 35 // 3. 36 do { 37 let printerResponse = try send(job: 1440, toPrinter: "Gutenberg") 38 print(printerResponse) 39 } catch PrintError.onFire { 40 print("I‘ll just put this over here, with the rest of the fire.") 41 } catch let printerError as PrintError { 42 print("Printer error: \(printerError).") 43 } catch { 44 print(error) 45 } 46 } 47 48 // 定义“打印错误”的枚举 49 enum PrintError: Error { 50 case outOfPaper 51 case noToner 52 case onFire 53 } 54 }
时间: 2024-10-08 09:45:28