Swiftでtry〜catch


スポンサーリンク

unc myFunc(value :Int) -> Int {
    var resultValue :Int = 0
    resultValue = value
    return resultValue
}

myFunc(1)


//throw the error
enum MyError :ErrorType {
    case InvalidValue
}

func doubleUp(value :Int) throws -> Int {
    if value < 0 {
        throw MyError.InvalidValue
    }
    
    return value * 2
}


do {
    var doubleResultValue = try doubleUp(-5)
    print("normaly end")
} catch MyError.InvalidValue {
    print("some error occured")
}


//defer
func longMethod() throws {
    sleep(1)
}

do {
    defer {
        print("end up time: \(NSDate())")
    }
    try longMethod()
    print("start up time: \(NSDate())")
} catch {
    print("error occured")
}