01. Handling of errors and exceptions

It will take about 3 minutes to finish reading this article.

1. Handlings of Objective-C

In Objective-C, we often write code like this:

1
2
3
4
5
NSError *error;
BOOL success = [data writeToFile: path options: options error: &error];
if(error) {
// something happens
}

That is a very good method to handle possible errors. However we often simply this code like this:

1
[data writeToFile: path options: options error: nil];

We set varaible error to nil, Maybe we don’t care about this error when we are developing. However this method can report errors. For example, if the space of the device’s disk is full, you will write unsuccessfully, and this error can’t not be found easily becase of our laziness.

2. Handlings of Swift

In Swift, we don’t need to write an pointer variable error that waiting to be written by called method. we can use ‘try catch’ to take place of it.

1
2
3
4
5
do {
try d.write(toFile: "Hello", options: [])
} catch let error as NSError {
print ("Error: \(error.domain)")
}

It is a very common to use ‘try catch’ to hand errors and exceptions in Swift. The sample code is as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
enum LoginError: Error {
case UserNotFound, UserPasswordNotMatch
}

func login(user: String, password: String) throws {
if !users.keys.contains(user) {
throw LoginError.UserNotFound
}
if users[user] != password {
throw LoginError.UserPasswordNotMatch
}
print("Login successfully.")
}
// call
let users:[String:String] = ["liudehua":"One", "wanggang":"Two", "liming":"Three"]
do {
try login(user: "ll", password: "234")
} catch LoginError.UserNotFound {
print("UserNotFound")
} catch LoginError.UserPasswordNotMatch {
print("UserPasswordNotMatch")
} catch {
//default handling, don't delete it, or it would report an error.
}