Swift try try! Try? Use and differences

swift exception handling in the History

  • Swift1.0 Cocoa Touch version of NSError, Swift does not really have its own exception handling mechanism
  • Swift2.0 version added ErrorType protocol
  • Swift3.0 version renamed Error protocol

Use of Swift3.0 Error protocol

First, the definition of an enumerated, integration protocol Error (Swift 2.0 protocol is called ErrorType, 3.0 renamed Protocol Error)

      
      
1
2
3
4
5
      
      
enum MyError : Error {
case one
case two
case three
}

Use throws and throw the

Throws back the parameter list used in a method of indicating an exception is thrown, the standard format: func 方法名字 (参数列表) throws -> 返回值类型using throw thrown in the method

      
      
1
2
3
4
5
6
7
8
9
10
11
12
      
      
func testFunc(str: String) throws -> String {
if str == "one" {
throw MyError.one
} else if str == "two" {
throw MyError.two
} else if str == "three" {
throw MyError.three
}
return "ok"
}

Using the do-catch handle exceptions

      
      
1
2
3
4
5
6
7
8
9
      
      
do {
var str = try testFunc(str: "three")
} catch MyError.one {
print( "MyError.one")
} catch MyError.two {
print( "MyError.two")
} catch let error as MyError {
print(error)
}

try?的使用

Swift2.0 后加入了新的关键字 try? , 如果不想处理异常那么可以用这个关键字,使用这个关键字返回一个可选值类型,如果有异常出现,返回nil.如果没有异常,则返回可选值.例子如下

      
      
1
2
3
4
5
6< 大专栏   Swift try try! try?使用和区别/div>
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
      
      
enum MyError : Error {
case one
case two
case three
}
func testFunc(str: String) throws -> String {
if str == "one" {
throw MyError.one
} else if str == "two" {
throw MyError.two
} else if str == "three" {
throw MyError.three
}
return "ok"
}
var str = try? testFunc(str: "three")
print(str)

控制台输出

`nil
Program ended with exit code: 0`

try!的使用

如果不想处理异常,而且不想让异常继续传播下去,可以使用try!.这有点儿类似NSAssert().但是一旦使用try!后,在可能抛出异常的方法中抛出了异常,那么程序会立刻停止.例子如下

      
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
      
      
enum MyError : Error {
case one
case two
case three
}
func testFunc(str: String) throws -> String {
if str == "one" {
throw MyError.one
} else if str == "two" {
throw MyError.two
} else if str == "three" {
throw MyError.three
}
return "ok"
}
var str = try! testFunc(str: "three")

控制台:程序奔溃掉~


try try? try! 的区别

  • try 出现异常处理异常
  • try? not handle the exception, an optional return value type, abnormal returns nil
  • try! prevent abnormal continue to spread, once the program appears to stop abnormal, similar NSAssert ()

Guess you like

Origin www.cnblogs.com/dajunjun/p/11698682.html
try