Last active
June 27, 2017 18:07
-
-
Save OctoberHammer/da9bd86d481ee0aaa48183daf3aaac19 to your computer and use it in GitHub Desktop.
try catch
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
//: Playground - noun: a place where people can play | |
import UIKit | |
import Foundation | |
enum MyErrors: Error { | |
case DivisionByZero | |
} | |
//MARK: Описываем функцию, которая будент выкидывать исключение, при попытке деления на ноль. | |
func divide(_ what: Float, by divider: Float) throws -> Float? { | |
if divider == 0.0 { | |
throw MyErrors.DivisionByZero | |
} | |
return what/divider | |
} | |
// | |
var result:Float = -100000.0 | |
//вызываем нашу функцию через блок ду-кэтч | |
do { | |
if let buffer = try divide(5.0, by: 0.0) | |
{ | |
result = buffer | |
} | |
}catch { | |
//в случае деления на 0, будет сообщено об ошибке | |
print(error) | |
//просто поставим какое-то значение-индикатор | |
result = 500000.0 | |
} | |
print(result) | |
//теперь через трай? | |
let anotherResult = try? divide(50.0, by: 0.0) | |
//в случае деления на 0 получаем nil | |
print("Second result: \(anotherResult)") | |
//При делении на 0 весь код ниже не выполнится вообще | |
if let thirdResult = try divide(10.0, by: 0.0) { | |
print("Third result: \(thirdResult)") | |
} else { | |
print("Something went wrong") | |
} | |
print("Just trying") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment