Swift ERROR : : Call can throw, but it is not marked with 'try' and the error is not handled

Swift ERROR : : Call can throw, but it is not marked with 'try' and the error is not handled

我刚开始学习 Swift 并且,我正在尝试将一首歌曲添加到我的代码中以在我按下按钮时播放它,但出现该错误。如何解决这个错误?

var buttonAudioPlayer = AVAudioPlayer()

@IBAction func btnWarning(sender: UIButton) {
    play()
}

override func viewDidLoad() {
    super.viewDidLoad()
}

func play() {
    let buttonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("warning", ofType: "mp3")!)
    let one = 1

    if one == 1 {
        buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL) //getting the error in this line
        buttonAudioPlayer.prepareToPlay()
        buttonAudioPlayer.play()
    }
}

编译器正确地告诉您初始化程序可以抛出错误,因为 method declaration 正确指出(例如,当 NSURL 不存在时):

init(contentsOfURL url: NSURL) throws

因此,您作为开发人员必须处理最终发生的错误:

do {
    let buttonAudioPlayer = try AVAudioPlayer(contentsOfURL: buttonAudioURL)
} catch let error {
    print("error occured \(error)")
}

或者您可以通过

告诉编译器调用实际上总是会成功
let buttonAudioPlayer = try! AVAudioPlayer(contentsOfURL: buttonAudioURL)

但这会导致您的应用程序崩溃 如果创建实际上没有成功 - 请小心。如果您尝试加载 的应用程序资源,您应该只使用第二种方法。

有可能AVAudioPlayer(contentsOfURL: buttonAudioURL)会抛出异常。所以你需要添加异常处理代码。

 do {
        try buttonAudioPlayer = AVAudioPlayer(contentsOfURL: buttonAudioURL)
    } catch {
        //handle exception here
    }