2017-08-31 68 views
-2

所以,我一直在製作一個基本的計算器。但我遇到了一個問題。 My code.如何處理NSException錯誤

@IBAction func calculate(_ sender: UIButton) { 
    let stringExpression = resultLabel.text! 
    let expression = NSExpression(format: stringExpression) 
    let result = expression.expressionValue(with: nil, context: nil) as! NSNumber 
    resultLabel.text! = String(result.doubleValue) // Writes response on textLabel :D 
}  

上述工程的代碼。但是,當輸入如5 ++ 6輸入時,它會崩潰我的應用程序。我不太清楚如何處理這個問題。

輸入無效輸入時會顯示以下錯誤。 The error given. libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

我不知道如何讓它顯示「錯誤」。 這應該適用於任何類型的錯誤。

+2

複製/粘貼代碼或錯誤消息,不顯示屏幕截圖。 – Larme

+0

固定:) @Larme –

+1

並沒有明確的錯誤信息?因爲我試過你的代碼,並得到了真正的(和有用的消息):「***由於未捕獲的異常'NSInvalidArgumentException'終止應用程序,原因:'無法解析格式字符串」5 ++ 6 == 1「'」而且它發生在「let expression = NSExpression(format:stringExpression)」。這是真實的信息來閱讀和提供您的問題。 – Larme

回答

0

必須將有效表達式傳遞給NSExpression初始化程序,否則將引發異常。沒有Swift唯一的方法來捕獲異常,所以唯一的可能性是確保只生成有效的輸入。

+0

或者:...使用一個採用Swift錯誤處理的objc包裝器。 –