Bas Bas - 4 months ago 23x
iOS Question

Try and Catch with NSUrl(fileURLWithPath)

I've been trying to implement try and catch in the following code

if let s = songId {
let track: NSURL!
track = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(s, ofType: "mp3")!)

I came up with the following code:

do {
track = try NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(s, ofType: "mp3")!)
catch let error as NSError {
print("NSURL Error: \(error.localizedDescription)")

But I get the following warnings:

No calls to throwing functions occur within 'try' expression


'catch' block is unreachable because no errors are thrown in 'do' block

And this is strange to me, because this construction usually works.
Only with
this construction isn't working. And I can't figure out why this is happening. Maybe it has something to do with it being an optional, but im not sure.
I can't figure out how to solve this. I need to use a try/catch or something similar, but I can't figure it out how to make it work.

I saw some similar problems on Google, but it didnt gave me an answer.
So my question is: How can I implement a try/catch construction or something similar with NSURL?

Thanks in advance.


There are no methods used that marked with throws keyword at the definition. So it really does not make much sense to wrap your code with try-catch. I would recommend to consider this:

let s = "song"
guard let filePath = NSBundle.mainBundle().pathForResource(s, ofType: "mp3") else {

    print("file not found in the app bundle: \(s).mp3")
    return false

let trackURL = NSURL(fileURLWithPath: filePath)
//continue with the url

Does it help?