Here's my Swift 2.1 code snippet. The error that's occurring is shown in the comments at the point where the error appears.
The error shows up in the debugging panel, and the app crashes. The app never prints the line in the catch, nor does it gracefully return as expected.
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
}
From everything I've seen, my do/try/catch format should be correct.
audioFile.readIntoBuffer returns void and has the keyword throws.
Yet, the catch is never executed.
What am I missing?
UPDATE: From Apple's documentation on AVAudioFile
For:
func readIntoBuffer(_ buffer: AVAudioPCMBuffer) throws
Under Discussion:
HANDLING ERRORS IN SWIFT:
In Swift, this API is imported as an initializer and is marked with the throws keyword to indicate that it throws an error in cases of failure.
You call this method in a try expression and handle any errors in the catch clauses of a do statement, as described in Error Handling in The Swift Programming Language (Swift 2.1) and Error Handling in Using Swift with Cocoa and Objective-C (Swift 2.1).
From The Swift Programming Language (Swift 2.1): Error Handline
NOTE
Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.
And, finally, from the same document:
Handling Errors Using Do-Catch
You use a do-catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it is matched against the catch clauses to determine which one of them can handle the error.
I don't have to write and throw my own errors/exceptions for them to be caught. I should be able to catch Swift's exceptions as well.
The do - catch combination is fine. This issue is simply one that cannot be caught - and therefore never makes it to the catch block.
If the issue were catchable (defined and handled via Swift's throws functionality), the catch block would've been executed.
Some semantics: there is a long-standing argument about the differences between the terms error and exception.
Some developers consider the two terms to be distinct. In this case, the term error represents an issue that was designed to be handled. Swift's throws action would fit here. In this case, a do - catch combination would allow the issue to be caught.
An exception, for these developers, represents an unexpected, usually fatal, issue that cannot be caught and handled. (Generally, even if you could catch it, you would not be able to handle it.)
Others consider the two terms to be equivalent and interchangeable, regardless of whether the issue in question can be caught or not. (Apple's documentation seems to follow this philosophy.)
(Updated to focus on the answer rather than the semantics.)
catch will only catch the errors that are explicitly thrown. It will never catch exceptions.
What you seem to have here is an exception happening in the AVAudioFile SDK, not a Swift error, so it's not caught:
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
In the context of Swift, "error" means an error thrown by a function, nothing else. The function being yours or not does not matter.
Exceptions in Swift are not caught ever. It's not the same as in Java at all, for example. In Swift, error != exception, they are two very different things.
I understand your opinion that "It should work for both" but it's simply not the case. You can see this as a semantic situation with using the keyword "catch" if you want, because it's the same keyword as other languages but behaves very differently; it resembles, but it's not the same.
As for your exception with AVAudioFile, I don't have a solution - maybe it's a bug in this SDK? Or it's not yet properly bind to Swift and the throwing system. In this case, and if nobody else has a solution, don't hesitate to report the bug to Apple.
see this example
struct E: ErrorType{}
func foo(i: Int) throws {
if i == 0 {
throw E()
}
print(10 / (i - 1))
}
do {
//try foo(1) // if you uncomment this line, the execution
// will crash, even though the function is declared
// as throwing and you use proper calling style (do / try / catch pattern)
try foo(0)
} catch {
print("error: ", error) // error: E()
}
Related
I notices some code that made me think the Exception function call was optional? E.g., do these two lines perform the same function?
throw Exception('oops!');
throw 'oops!'
No.
The former, throw Exception('oops!');, creates a new Exception object using the Exception constructor, then throws that object.
It can be caught by try { ... } on Exception catch (e) { ... }.
The latter, throw 'oops!'; throws the string object.
It can be caught by try { ... } on String catch (e) { ... }.
Generally, you shouldn't be doing either.
If someone made an error, something that would have been nice to catch at compile-time and reject the program, but which happens to not be that easy to detect, throw an Error (preferably some suitable subclass of Error).
Errors are not intended to be caught, but to make the program fail visibly. Some frameworks do catch errors and log them instead. They're typically able to restart the code which failed and carry on, without needing to understand why.
If your code hit some exceptional situation which the caller should be made aware of (and which prevents just continuing), throw a specific subclass of Exception, one which contains the information the caller needs to programmatically handle that situation. Document that the code throws this particular exception. It's really a different kind of return value more than it's an error report. Exceptions are intended to be caught and handled. Not handling an exception is, itself, an error (which is why it's OK for an uncaught exception to also make the program fail visibly).
If you're debugging, by all means throw "WAT!"; all you want. Just remove it before you release the code.
I found some crashes in my app despite of try? construction. The firebase crashlytics logged
Fatal Exception: NSInvalidArgumentException
Invalid number value (infinite) in JSON write
Here is a test example
let avgSpeed = 0.1 / 0
print(avgSpeed)
let data = ["average_speed" : avgSpeed]
if let body = try? JSONSerialization.data(withJSONObject: [data]) {
print("success")
} else {
print("unable to make body for call")
}
Why did that happen?
iOS 13, swift 4
try? does not catch exceptions. It catches thrown errors. Those are different things in Swift. Exceptions are at the Objective-C level and cannot be caught by Swift at all (they can't be safely caught in ObjC in most cases either, but that's a different discussion).
The solution in this case is to use JSONEncoder rather than JSONSerialization. JSONEncoder is a pure-Swift system. JSONSerialization is bridged from ObjC.
let body = try? JSONEncoder().encode([data])
See Handling Errors for more information:
Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.
If you want to use JSONSerialization, it's important to recognize that it is a programming error to call it this way. The exception is intended to crash the program (even in ObjC). The correct way to write this code is:
if JSONSerialization.isValidJSONObject([data]), // <=== first, check it is valid
let body = try? JSONSerialization.data(withJSONObject: [data]) {
print("success")
} else {
print("unable to make body for call")
}
See the docs for more information:
If obj will not produce valid JSON, an exception is thrown. This exception is thrown prior to parsing and represents a programming error, not an internal error. You should check whether the input will produce valid JSON before calling this method by using isValidJSONObject(_:).
The thrown error from JSONSerialization is only to indicate an internal error in the serializer, not an attempt to encode an invalid object:
error
If an internal error occurs, upon return contains an NSError object with code NSPropertyListWriteInvalidError that describes the problem.
What is the difference between catch(e) and on Exception catch(e) in dart?
AVOID catches without on clauses.
Using catch clauses without on clauses makes your code prone to encountering unexpected errors that won't be thrown (and thus will go unnoticed).
BAD:
try {
somethingRisky()
} catch(e) {
doSomething(e);
}
GOOD:
try {
somethingRisky()
} on Exception catch(e) {
doSomething(e);
}
Link: avoid_catches_without_on_clauses
The } on Exception catch (e) { will catch all thrown objects implementing Exception.
The excludes most errors (which implement Error),
The } catch (e) { will catch all thrown objects, both exceptions and errors - and anything else that might get thrown. Most thrown objects implement either Exception or Error, but that's just a convention. Any non-null object can be thrown.
I'd actually recommend against on Exception as well. Exceptions are not errors, they are intended for functions as an alternative to returning a value, but exceptions are still just as much part of the function API, and you should only be catching the exceptions that you are actually planning to handle. Since Exception itself has no information, you should be catching the subtype that the function is documented as throwing so you can use the available information to handle the exceptional case.
If you are not going to handle it, you might as well treat the exception as an error.
Using only } catch (e) { to catch everything is reasonable in some situations, mainly in framework code which wraps other user code, and needs to make sure a user code error or unhandled exception doesn't take down the entire program.
I have an iOS application written in Swift 2 in Xcode 8.2.1, that's built for iOS 10.2.
I've had a number of crash reports from TestFlight and despite symbolication, none of the crash logs show any program state besides the stack-traces (no argument values, no locals, no heap objects, etc).
...but inside those functions I can see code which is likely to fail (e.g. a forced unwrap) but the crash log isn't telling me where or why it's failing.
When debugging in Xcode, I can use fatalError(message: String) where I can put my own message like "functionFoo returned nil" or "variable bar == \"" + bar + "\"", except when deployed using TestFlight or the App Store the fatalError will be hit and the program terminates, but the message value is not saved to the crash log, making it pointless.
In other environments, like C#/.NET and Java I can simply throw new SomeExceptionType("my message") and all information is available in whatever global catch(Exception) handler I have.
How can I achieve the same goal in iOS / Swift?
Swift does support error handling. You can create your own error type by confirming to Error protocol or use existing error types and then throw an error by invoking throw error.
But Swift forces you add error handling to any code that can throw an error. There are multiple way you can handle error in swift.
Apply throws keyword to your function, this indicates that the function can throw an error when invoked and the error should be handled by the caller.
func canThrowErrors() throws -> String
When invoking methods with throws keyword you have to add try keyword at the beginning of the invocation. All these try invocations should be handled either by applying throws to method to just propagate the errors or wrapping inside a do-catch block:
do {
try canThrowErrors()
try canThrowOtherErrors()
} catch is SpecificError {
// handling only specific error type
} catch let error as SpecificError {
// catches only specific error for type
} catch {
// catches all errors
}
Additionally you can use try? and try! for throwing function invocation to disable error propagation and retrieve optional result that returns nil in case of error and runtime assertions respectively.
By forcing you to handle all the errors at compile time swift avoids any undefined runtime behavior and debugging nightmare.
I would suggest to use fatalError or any other runtime assertion only if scenarios when there is no way to recover from a state without crashing the app. Unfortunately, there is no way to handle errors from fatalError as its use is only reserved for such scenarios only. Also, in your crashlog you will only get the line number that caused the crash to get additional info for the cause of crash I would suggest to use custom logging or analytics.
In Swift, NSKeyedUnarchiver.unarchiveObjectWithData(data) will throw an exception if data can't be unarchived.
There are some situations where we have no guarantee if that the data is not corrupted, such as when reading from a file.
I am not aware of a try/catch mechanism in Swift, nor that I know of a method like canUnarchive that would help prevent the exception.
Besides implementing the try/catch in Obj-C, is there a pure Swift solution to this problem?
Because unarchiveObjectWithData() doesn't throw its exception, there is currently no way to catch it in Swift (as of writing). The iOS 9 SDK has added a new NSKeyedUnarchiver method decodeTopLevelObject() which now throws an error. You can catch this with the do, try, catch control flow.
do {
let result = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(NSData(...))
} catch {
print(error)
}