Inside do block use try keyword to call Function that can throw error.
If Function throws error program jumps to catch block that relates to the thrown error.
do...catch
//DECLARE ENUMERATOR WHICH CAN BE USED TO THROW EXCEPTIONS.
enum VendingMachineError : Error {
case InvalidSelection
case InsufficientFunds(coinsNeeded: Int)
}
//DECLARE FUNCTION WHICH CAN THROW EXCEPTION.
func canThrowErrors() throws -> String {
var error = 2
if (error==1) { throw VendingMachineError.InvalidSelection }
if (error==2) { throw VendingMachineError.InsufficientFunds(coinsNeeded: 5) }
}
//DECLARE DO-CATCH BLOCK.
do {
try canThrowErrors() //Call function that can throw exception.
print("This line is skipped")
}
catch VendingMachineError.InvalidSelection {
print("InvalidSelection")
}
catch VendingMachineError.InsufficientFunds {
print("InsufficientFunds")
}