0
我正在處理一個我已經實現了do-try-catch子句的類。 基本問題是,經過「嘗試」的代碼,即使嘗試失敗得到了執行:Swift Do Try Catch行爲
Do{
try jsonparshing(mydata)
code....
}catch{
alert("error")
}
是否正確定位代碼嘗試後? 如果嘗試失敗,我不希望此代碼得到執行。
我正在處理一個我已經實現了do-try-catch子句的類。 基本問題是,經過「嘗試」的代碼,即使嘗試失敗得到了執行:Swift Do Try Catch行爲
Do{
try jsonparshing(mydata)
code....
}catch{
alert("error")
}
是否正確定位代碼嘗試後? 如果嘗試失敗,我不希望此代碼得到執行。
這裏是我會做調試行爲的步驟:
(1)貴 'jsonparshing(MYDATA)' 真摔?
1.a.你可以檢查throws關鍵字的'jsonParsing(_ :)'的類型。
1.b.或者你可以嘗試省略'do {} catch {}'和'try'以查看Xcode是否抱怨函數拋出並且應該使用try。
// btw。是一個錯字?也許'jsonParsing(myData)'更加自定義。 (2)假設你過去登記(1)。即該功能真的扔了。然後你可以用模擬替換你的'jsonParsing(_ :)',只是爲了說服你自己Swift的'do catch {}'確實有效。代碼中可能有其他可能導致意外行爲的其他內容。
enum SimpleError: Error {
case userError(msg: String)
case systemError(msg: String)
}
func alwaysThrow() throws ->() {
throw SimpleError.userError(msg: "I create error!")
}
do {
print("before throw") // printed
try alwaysThrow()
print("after throw") // not printed
} catch {
print(error) // print: "userError("I create error!")\n"
}
(三)在這一點上,如果它不是一個用戶/編程錯誤,那麼你的注意力集中在「jsonParsing(_ :)」,因爲在這裏的罪魁禍首是。
如果'try'失敗,執行到'catch'。失敗的'try'後面的代碼沒有被調用。 – rmaddy
如果方法失敗,該方法真的會拋出一個錯誤嗎? – vadian