swift——异常处理

FileManager.swift

import UIKit

enum FileReadError : Error {
    case fileNameNotNull
    case filePathNotFind
    case fileDataError
}

class FileManager: NSObject {
    func readFileContent(_ fileName : String) throws -> String? {
        // 1.判断文件名字是否为""
        if fileName == "" {
            // 抛出异常,当抛出异常时,后续方法不再执行
            throw FileReadError.fileNameNotNull
        }
        
        // 2.获取文件的路径
        guard let filePath = Bundle.main.path(forResource: fileName, ofType: nil) else {
            // 抛出异常
            throw FileReadError.filePathNotFind
        }
        
        // 3.读取文件中的内容
        guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else {
            // 抛出异常
            throw FileReadError.fileDataError
        }
        
        // 4.读取到信息
        return String(data: data, encoding: String.Encoding.utf8)
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController {
    
    var manager = FileManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        
        
        do {
            let str = try manager.readFileContent("123.txt")
            print(str)
        } catch {
            let errorType = error as! FileReadError
            switch errorType {
                case FileReadError.fileNameNotNull:
                    print("123")
                case FileReadError.filePathNotFind:
                    print("321")
                case FileReadError.fileDataError:
                    print("122")
            }
        }
        
    }
}

你可能感兴趣的:(swift——异常处理)