尝试使用 NSUrl(fileURLWithPath) 捕捉

Try and Catch with NSUrl(fileURLWithPath)

我一直在尝试在下面的代码中实现 try 和 catch

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

我想出了以下代码:

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

但我收到以下警告:

No calls to throwing functions occur within 'try' expression

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

这对我来说很奇怪,因为这种结构通常有效。 只有 NSURL 这个结构不工作。我不明白为什么会这样。也许这与它是可选的有关,但我不确定。 我不知道如何解决这个问题。我需要使用 try/catch 或类似的东西,但我不知道如何让它工作。

我在Google上看到了一些类似的问题,但没有给我答案。 所以我的问题是:如何使用 NSURL 实现 try/catch 构造或类似的东西?

提前致谢。

没有使用定义中用throws关键字标记的方法。所以用 try-catch 包装你的代码真的没有多大意义。我建议考虑这个:

let s = "song"
guard let trackURL = NSBundle.mainBundle().URLForResource(s, withExtension: "mp3") else {
  print("File not found in the app bundle: \(s).mp3")
  return false
}

有帮助吗?

该初始化程序不会失败,也不会抛出或失败,因此 try/catch 块是不必要的。声明为:

public init(fileURLWithPath path: String)

如果它可能抛出错误,则声明为:

public init(fileURLWithPath path: String) throws

或者如果它可能失败而不抛出错误,它将被声明为:

public init?(fileURLWithPath path: String)

如果您确定捆绑包中始终包含您要查找的曲目,那么您可以使用

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