Created
August 15, 2017 06:39
-
-
Save scorpiozj/0c9e6333e0c493ea2912da4d4e8b7066 to your computer and use it in GitHub Desktop.
Swift Error Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ViewController.swift | |
// ErrorTest | |
// | |
// Created by ZhuJiang on 2017/8/15. | |
// Copyright © 2017年 Charles. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
do { | |
try errorTest(num: -10.0) | |
} catch let error { | |
print("\(error)") | |
} | |
let x = try? errorTest(num: -10.0) | |
print(type(of: x)) | |
let y = try? errorTest(num: 10.0) | |
print(type(of: y)) | |
let z = try! errorTest(num: 10.0) //crash if it is -10.0 | |
print(type(of: z)) | |
} | |
enum ZZNumberError : Error { case negativeError } | |
private func errorTest(num: Double) throws -> Double { | |
if num < 0 { | |
throw ZZNumberError.negativeError | |
} | |
return num | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment