Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Categorize ErrorHandling

to4iki
January 21, 2017

Categorize ErrorHandling

error-handling/exception mechanism tips

to4iki

January 21, 2017
Tweet

More Decks by to4iki

Other Decks in Programming

Transcript

  1. Pros • “ྫ֎ͷ࠷େͷར఺͸ɺແࢹͰ͖ͳ͍ํ๏ͰΤ ϥʔঢ়ଶΛ஌ΒͤΔ͜ͱͰ͋Δ” • “ྫ֎ΛΩϟον͢Δओͳ໨త͸ɺΤϥʔͷݪ ҼΛऔΓআ͍ͯɺճ෮͢Δ͜ͱ” via .NET •

    ൃੜͨ͠Τϥʔͷ಺༰Λత֬ʹදݱͰ͖Δ • ൚༻తʹΤϥʔΛѻ͏͜ͱ͕ग़དྷΔ • Τϥʔͷѻ͍ํΛମܥԽͰ͖Δ => ίʔυ ʹҰ؏ੑΛ࣋ͨͤΔ͜ͱ͕ग़དྷΔ
  2. Cons • ຊདྷͷॲཧͷྲྀΕΛͿͬͨ੾ͬͯ”େҬ୤ग़”Ͱ͖͏Δ • ΦϒδΣΫτࢦ޲ͱͷ෇͖߹͍ํ͕೉͍͠ • લޙঢ়ଶΛ஌ࣝͱͯ࣋ͭ͠ඞཁ͕͋Δ • ୭ͷ੹೚ͱ͢Δ͔͕ •

    டংΛอͨͳ͍ͱΧΦε(खൈ͖͠Α͏ͱࢥ͑͹͍͘ΒͰ΋ग़དྷΔ) • ྫ֎͕ѲΓͭͿ͞ΕΔ • ͳΜͰ΋͔ΜͰ΋ྫ֎ʹแΉ
  3. func toInt(s: String) -> Int? guard let i = toInt(s:

    "1") else { print("enter an integer") return } // execute using `i: Int`
  4. func loadFile(at path: String) throws -> File do { let

    file = try loadFile(at: path) // execute using `file` } catch FileError.noSuchFile { // Error handling when there is no file } catch FileError.permissionDenied { // Error handling when there is no permission } catch { // Error handling in other cases }
  5. 3. Universal error • ϓϩάϥϜ͕ఀࢭ͢Ε͹͍͍ɺΤϥʔॲཧΛ͢Δඞཁ͸ͳ͍ͱߟ͑Δ৔ ߹ʹ࠾༻ • fail fast: ߈ܸతϓϩάϥϛϯά,

    ૣΊʹΫϥογϡͤ͞Δ • த్൒୺ʹಈ͍͍ͯΔΑΓࢮΜͩϓϩάϥϜͷํ͕μϝʔδ͕গͳ͍ • ݎ࿚ੑΑΓਖ਼౰ੑΛॏࢹ͢Δέʔεʹ͓͍ͯ࢖༻͢Δ(ෆਖ਼֬ͳ݁Ռ Λฦ͞ͳ͍͜ͱ) • ճ෮ෆೳ • ex. ϝϞϦෆ଍΍ελοΫΦʔόʔϑϩʔɺϓϥάϥϜ্هड़͕ඞཁͩ ͕ى͜Γಘͳ͍έʔε
  6. required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    func doSomething(s: String) { switch s { case "a": // ... case "b": // ... default: // unreachable fatalError("The impossible occurred") } }
  7. 4. Logic failure • ex. ͦͷҾ਺͕དྷΔ͜ͱࣗମ͕όάɺίʔυΛमਖ਼͢Δඞཁ͕͋ Δͱߟ͑Δ৔߹ʹ࠾༻ • ࣮ߦ࣌ʹىͬͯ͜͸͍͚ͳ͍ͷͰɺىͬͨ͜৔߹ͷڍಈ͸ະఆٛ •

    ࠷దԽ → ࣮ߦ࣌ͷ҆શੑνΣοΫ͸ߦΘͳ͍ → Φʔόʔϔο υΛ཈͑Δ • ex. nil͕ೖ͍ͬͯΔOptionalʹରͯ͠ Forced unwrapping, ഑ྻ ͷଘࡏ͠ͳ͍ΠϯσοΫε΁ͷΞΫηεͳͲ
  8. func printEvenSquare(_ i: Int) { precondition(i % 2 == 0)

    print("even: \(i * i)") } printEvenSquare(5) // crash if odd number
  9. assert/precondition/fatalError • -Onone: Compile without any optimization == debug build

    • -O: with optimizations == release build • -Ounchecked: Compile with optimizations and remove runtime safety checks http://safx-dev.blogspot.jp/2015/02/swift-assert-precondition-and-fatalerror.html
  10. Conclusion • ྫ֎(Τϥʔ)ػߏΛ࢖͏໨త͸ɺແࢹͰ͖ͳ͍ํ๏Ͱঢ়ଶΛ஌ΒͤΔ͜ͱ • “ͲͷΑ͏ʹରԠ͍͔ͤͨ͞”ͰɺΤϥʔΛ෼ྨ͢Δ • લఏ৚͕݅໌֬ → Simple domain

    error • ݪҼ͝ͱʹରԠ → Recoverable error • ճ෮ෆೳ → Universal error • ίʔυͷޡΓ → Logic failure • Τϥʔ෼ྨ͕ద੾Ͱ͋Ε͹ɺடং͕อͨΕΔ͸ͣ
  11. See also • ྫ֎ઃܭʹ͓͚Δେࡑ http://www.slideshare.net/t_wada/exception-design-by-contract • ྫ֎ೖ໳Ҏલ http://qiita.com/Kokudori/items/3a953c00012408f76ab9 • Java/Androidʹ͓͚Δྫ֎ઃܭɺ͋Δ͍͸ʮܖ໿ʹΑΔઃܭʯʹΑΔγϯϓϧ͞ͷ௥ٻ

    http://qiita.com/yuya_presto/items/3b651d6b0cf38f77e933 • ྫ֎ઃܭͷ࿩ https://gist.github.com/sunaot/6138546 • ͳͥGoݴޠ(golang)͸Α͍ݴޠͳͷ͔ɾGoͰϓϩάϥϜΛॻ͘΂͖ͳͷ͔ http:// www.yunabe.jp/docs/why_golang_is_good.html • Three Stories about Error Handling in Swift http://koherent.org/tryswift/codes.html