这是我的 Swift 2.1 代码片段。发生的错误显示在错误出现处的注释中。
错误显示在调试面板中,并且应用程序崩溃。该应用程序永远不会打印 catch 中的行,也不会按预期优雅地返回。
let audioFileURL = receivedAudio.filePathURL
guard let audioFile = try? AVAudioFile(forReading: audioFileURL) else {
print("file setup failed")
return
}
let audioFileFrameCount = AVAudioFrameCount(audioFile.length)
audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFile.fileFormat, frameCapacity: audioFileFrameCount)
do {
// ERROR: AVAudioFile.mm:263: -[AVAudioFile readIntoBuffer:frameCount:error:]: error -50
// Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'error -50'
// -50 = Core Audio: bad param
try audioFile.readIntoBuffer(audioFileBuffer)
}
catch {
print("unable to load sound file into buffer")
return
}
从我所看到的一切来看,我的 do/try/catch 格式应该是正确的。
audioFile.readIntoBuffer
回报void
并且有关键字throws
.
然而,catch 永远不会被执行。
我缺少什么?
UPDATE: 来自Apple关于AVAudioFile的文档 https://developer.apple.com/library/prerelease/ios/documentation/AVFoundation/Reference/AVAudioFile_Class/index.html#//apple_ref/occ/instm/AVAudioFile/initForReading:error:
For:
func readIntoBuffer(_ buffer: AVAudioPCMBuffer) throws
Under 讨论:
处理 Swift 中的错误:
在 Swift 中,此 API 作为初始值设定项导入,并使用 throws 关键字进行标记,以指示在失败时抛出错误。
您可以在 try 表达式中调用此方法,并处理 do 语句的 catch 子句中的任何错误,如《Swift 编程语言 (Swift 2.1)》中的错误处理和《将 Swift 与 Cocoa 和 Objective-C 一起使用》中的错误处理 (Swift 2.1) 中所述。 )。
From Swift 编程语言 (Swift 2.1):错误处理 https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
NOTE
Swift 中的错误处理类似于其他语言中的异常处理,使用 try、catch 和 throw 关键字。与许多语言(包括 Objective-C)中的异常处理不同,Swift 中的错误处理不涉及展开调用堆栈,这一过程的计算成本可能很高。因此, throw 语句的性能特征与 return 语句的性能特征相当。
最后,来自同一份文档:
使用 Do-Catch 处理错误
您可以使用 do-catch 语句通过运行代码块来处理错误。如果 do 子句中的代码抛出错误,则会将其与 catch 子句进行匹配,以确定哪一个子句可以处理该错误。
我不必编写并抛出自己的错误/异常来捕获它们。我也应该能够捕获 Swift 的异常。