Swift Errors Handling

Error handling is an mechanism to control error situation at runtime. This error is based on logical condition and system failure situation. This error is also known as Exception Because that are terminates program execution abnormally. That are very dangerous because that are occur during program execution and one exception can destroy the flow of execution.

Generally exception are occured of two main reason. First is logical error and second is system failure. logical error are occurred unaccepted operation and input results, And other is system resources fail by any outer interrupts. So programer are responsible to handle first type of exception logical system failure situation. Because second type of exception is based on system resource and environment.

Swift is providing a mechanism to handle unaccepted logical situation those to control unwanted error colossally. This mechanism is called error handling.

//Error controle case
enum ErrorList:Error{
    case divideByZero
}
//Divide a number
func divide(dividend:Int ,divisor:Int) throws -> Int{

    if(divisor==0){
        throw ErrorList.divideByZero
    }else{
        return dividend / divisor
    }
}
do{
    var result = try divide(dividend:12,divisor:4)
    print("Case 1 result : \(result)")

    result = try divide(dividend:12,divisor:0)
    print("Case 2 result : \(result)")
    
}catch ErrorList.divideByZero{
    //Catch custom error
    print("You can't divide a number by zero ")

}

Output

Case 1 result : 3
You can't divide a number by zero 

Note that we can handle most of logical error by using if-else condition but that is not suitable for all development process. This exception handling mechanism are useful to clear indication of codes.

enum ErrorReport:Error{
    case missingValue(String)
}
do{
   let a=""
   if(a==""){
        throw ErrorReport.missingValue("value are missing")
   }
   else{
        print("\(a)")
   }
}catch let error{
    print("\(error)")
}

Output

missingValue("value are missing")

Example

//Handle mutiple error
enum ErrorReport:Error{
    case missingValue
    case divideByZero
    case invalidDiscount(discount:Int)
}
class Product{
    
    var name :  String
    var price : Double
    var discount : Double

    init(_ name:String,_ price:Double) throws{
        guard name != "" else{
            //When not provide product name
            throw ErrorReport.missingValue
        }
        self.discount=0.0
        self.name=name
        self.price=price
    }
    func discountPay(_ discount:Int) throws{
        // Ensure that valid discount
        guard discount < 100 else {
            //When discount rate exceed limit
            throw ErrorReport.invalidDiscount(discount:discount)
        }
        let doubleValue=Double(discount)
        self.discount=(price*doubleValue)/100
    }
    func details(){
        print("Product Name : \(name)")
        print("Product Price : \(price)")
        print("Product Discount : \(discount)")
    }
}
do{
    //Case 1
    print("Pen Drive Details")
    let penDrive = try Product("Pen Drive",100)
    try penDrive.discountPay(50) //Set % of discount
    penDrive.details()

    //Case 2
    print("iPhone Details")
    let iphone = try Product("I phone",78000)
    try iphone.discountPay(110) //Set % of discount
    iphone.details() //When no error

}catch let error as ErrorReport {
    //Handle the multiple user defined errors
    switch(error){

        case .missingValue:
            print("Missing name")
        case .divideByZero:
            print("Divide by Zero") 
        case .invalidDiscount(let discount):
            print("Invalid Discount : \(discount) % ")      
    }
}

Output

Pen Drive Details
Product Name : Pen Drive
Product Price : 100.0
Product Discount : 50.0
iPhone Details
Invalid Discount : 110 % 


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved