Swift - 12 错误
2022-03-20 本文已影响0人
aven_kang
Swift 中可以通过Error协议自定义运行时错误信息
enum SomeError : Error {
case illegalArg(String)
case outOfBound(Int,Int)
case outOfMemory
}
func divide(_ num1: Int, _ num2: Int) throws -> Int {
if num2 == 0 {
throw SomeError.illegalArg("0不能作为除数")
}
return num1/num2
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
do {
print("2")
try divide(10, 0) // 如果这里就抛出异常了,那么后面的打印也不会进行了[图片上传中...(截屏2022-02-24 下午8.46.17.png-85ba5d-1645706788983-0)]
print("3")
print("4")
print("5")
} catch let SomeError.illegalArg(msg){
print(msg)
} catch {
print("test")
}
}
}
截屏2022-02-24 下午8.46.17.png