"Learn Swift from scratch" study notes (Day54) - throwing errors

 

Original article, welcome to reprint. Please indicate: Guan Dongsheng's blog

 

It is required to call a function or method after try . They may throw an error. The throws keyword should be added after the parameters declared by these functions or methods, indicating that the function or method can throw errors.

The sample code for declaring a throwing error method is as follows:

//Delete Note record method
func remove(model: Note) throws {
  ...
}
//Query all record data method
func findAll() throws -> [Note] {
    ...
}

 

The above code remove(_:) method has no return value, and the throws keyword is placed after the parameter. findAll() has the return value throws keyword placed between the parameter and the return value type.

 

throw an error in a function or method

A function or method can declare to throw an error because the error is generated and thrown in the function or method, so the function or method declaration throwing error has practical meaning.

In the way that produces and throws an error:

<!--[if !supportLists]--> l   <!--[endif]--> Throw an error artificially through a throw statement in a function or method .

<!--[if !supportLists]--> l   <!--[endif]--> Other functions or methods called in a function or method that can throw an error, but without catching processing, will cause the error to be propagated .

The sample code is as follows:

// delete the Note method
func remove(model: Note) throws {       
   
    guard let date = model.date else { //Judging that there is a guard statement when throwing
        // throws "primary key is null" error
        throw DAOError.PrimaryKeyNull     
    }
    //Compare date primary keys for equality
    for (index, note) in listData.enumerate() where note.date == date {
        listData.removeAtIndex(index)
    }
}
 
// query all data methods
func findAll() throws -> [Note] {       
   
    guard listData.count > 0 else { //Judging that there is a guard statement when throwing
        // Throws a "no data" error.
        throw DAOError.NoData         
    }
    return listData
}
 
func printNotes() throws { // declare throws error
   
    let datas  = try findAll()       
    for note in datas {
        print("date : \(note.date!) - content: \(note.content!)")
    }
}
try printNotes()     

            

The guard statement is best at handling this kind of early judgment, throwing an error if the condition is false .

The findAll() statement itself may generate an error, but it is not caught and processed by the catch statement, which causes the error to propagate to the caller of the function or method. If its caller does not catch and process, then the final program A runtime error occurs.

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327079334&siteId=291194637