Updating to 2.0 with Xcode 7 Beta 4
I have this code block
do
{
try AVAudioSession.sharedInstance().setActive(true)
} catch let err as NSError
{
println("Dim background error")
}
And its giving me the error (on the try
line)
Errors thrown from here are not handled.
Is this a compiler error or is there something I am missing in my syntax?
I checked the docs and my code 'looks' correct.
There are four ways to handle errors in Swift. You can propagate the error from a function to the code that calls that function, handle the error using a do - catch statement, handle the error as an optional value, or assert that the error will not occur.
Creating a throwing method is as easy as adding the throws keyword to a method just before the return statement. In this example, we use a method to update the name for a user of a specific user identifier. This means that you have to use the try keyword before a piece of code that can throw an error.
In Swift 2.0, Apple introduced the throws keyword in Swift. This keyword is so helpful for us on error handling. Basically throws keyword allows us to throw errors inside a method, property, class, or struct. After async/await came out with Swift 5.5, throwing functions became more popular.
What types of errors can AVAudioSession.sharedInstance().setActive(true)
throw?
If it can only throw NSError
s, then there's no need of specifying this when catching the error. You could simply write:
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Dim background error")
}
If you want to use the error in your catch
-scope, you can still access it. Swift automatically binds the thrown error to error
, which can be used:
catch {
// do something with `error`
}
If the method throws multiple types of errors, and you only want to deal with the ones that are NSError
s, you can conditionally bind them:
catch let specialError as NSError {
// do something with `specialError`
}
You must ensure though, that every thrown error is handled. So assuming that the method can also throw a RandomError
(which I just made up now), you would have to write:
catch let randomError as RandomError {
// do something with `randomError`
}
...in addition to the catch
of the NSError
.
Or you could of course use the general case:
catch {
// do something with `error`
}
So I assume your problem can be solved by removing let err as NSError
, from your catch
-statement.
May be a compiler bug. Anyway try removing let err as NSError
; catch
alone is enough if you want to catch all errors.
Also, with Swift 2 you should use print
, not println
.
The following code compiles without errors with XCode 7 Beta 4:
import AVFoundation
class X {
func y() {
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print("Dim background error \(error)")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With