0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

try do catch構文について

Posted at

try do catchについて理解を得たのでまとめ
まずはコードから

enum HogeError: Error {
    case hoge
    case hogehoge
    case hogehogehoge
}

class Hoge {
    class func hoge() throws -> String {
        if !false {
            throw HogeError.hogehogehoge
        }
        return "成功"
    }
}

class Hogehoge {
    class func hoge() -> String {
        do {
            _ = try Hoge.hoge()
        } catch HogeError.hoge {
            return "hoge"
        } catch HogeError.hogehoge {
            return "hogehoge"
        } catch HogeError.hogehogehoge {
            return "hogehogehoge"
        } catch {
            return "来ない"
        }
        return "成功"
    }
}

・エラーハンドリング(HogeError)を列挙型で定義(プロトコルErrorに準拠させる)
・Hogeクラスのhogeメソッドはエラーを投げているのでメソッドに「throws」を書く必要がある(エラーを投げていると明示するため)
・Hogehogeクラスのhogeメソッドでdo catch構文を実装
・doで実装しエラーが返ってきたらcatchでエラー実装をする(ログを出すなど)
・エラー処理を複数実装することができる(最後のcatchは来ないが実装必須)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?