為什麼要使用「例外處理」
- 提高程式的可靠性: 通過處理異常,我們可以避免程式因為異常情況而崩潰或產生未預期的行為,從而提高程式的可靠性。
- 提供更好的反饋: 使用例外處理可以提供更具描述性的錯誤訊息,幫助開發者快速定位並修復問題。
- 增加程式的容錯性: 通過捕獲和處理異常,我們可以使程式在面對錯誤時優雅地回退或提供替代方案,從而增加程式的容錯性。
- 改善程式的可讀性: 通過將異常處理代碼與正常業務邏輯分離,可以使程式的結構更清晰、更易於理解。
語法
Swift使用do
、try
、catch
和throw
關鍵字來進行異常處理。以下是基本語法:
enum MyError: Error {
case runtimeError(String)
}
func riskyFunction() throws {
throw MyError.runtimeError("Something went wrong")
}
do {
try riskyFunction()
} catch MyError.runtimeError(let message) {
print("Caught a runtime error: \\\\(message)")
} catch {
print("Caught an unknown error")
}
常見異常類型
Swift中有許多內建的異常類型,這些異常通常是基於Error
協議定義的。常見的異常類型包括:
URLError
: 代表URL相關的錯誤。CocoaError
: 代表Cocoa框架中的錯誤。DecodingError
: 代表解碼過程中的錯誤。EncodingError
: 代表編碼過程中的錯誤。
enum FileError: Error {
case fileNotFound
case unreadable
case encodingFailed
}
func readFile(at path: String) throws -> String {
guard path == "validPath" else {
throw FileError.fileNotFound
}
return "File content"
}
do {
let content = try readFile(at: "invalidPath")
print(content)
} catch FileError.fileNotFound {
print("File not found")
} catch FileError.unreadable {
print("File unreadable")
} catch {
print("Other error: \\\\(error)")
}
主動觸發異常訊息
你可以使用throw
關鍵字來主動觸發異常。這在需要主動檢查條件並拋出錯誤時非常有用。
enum ValidationError: Error {
case invalidInput(String)
}
func validate(input: String) throws {
guard input.count >= 5 else {
throw ValidationError.invalidInput("Input is too short")
}
}
do {
try validate(input: "abc")
} catch ValidationError.invalidInput(let message) {
print("Validation error: \\\\(message)")
}
主動觸發用戶自定義異常訊息
你可以定義自己的異常類型並在適當的地方拋出自定義異常。
enum CustomError: Error {
case customError(String)
}
func performOperation() throws {
throw CustomError.customError("This is a custom error")
}
do {
try performOperation()
} catch CustomError.customError(let message) {
print("Caught custom error: \\\\(message)")
}
這些例子展示了如何在Swift中進行異常處理,使用do
、try
、catch
和throw
關鍵字來捕獲和處理異常,提高程式的可靠性、容錯性和可讀性。學會這些技術可以幫助你編寫更健壯和易於維護的Swift應用程序。