エラーハンドリング - Swift

最終更新日: 2026-07-26

TOP(About this memo)) > 一覧(Swift) > エラーハンドリング

エラーを投げる(throws, throw)

func メソッド名(引数名: ) throws -> 戻り値 {
    // エラーを投げる可能性のある処理を記述
    throw エラーを投げる処理内容
}

do try catch

do {
    try 
} catch CocoaError.fileNoSuchFile {
    // ファイルやディレクトリが見つからなかった場合の処理
    // この書き方の場合は、自動的に変数errorがError型として値が入っている。
} catch CocoaError.fileLocking {
    // ファイルがロックされている場合の処理
} catch {
    // その他のエラー時
}
} catch let error as CocoaError {
    // CocoaErrorだったときの共通処理
    doSomething()

    switch error.code {
    case .fileNoSuchFile:
        // ファイルやディレクトリが見つからなかった場合の処理
    case .fileLocking:
        // ファイルがロックされている場合の処理
    default:
        // その他のCocoaError時
    }
} catch let error as  {
} catch {
    // その他のエラー時
}
enum CustomError: Error {
    case something(message: String)
}
do {
    throw CustomError.something(message: "何かのエラーです")
} catch CustomError.something(let message) {
    print(message)
} catch {
    // 何かエラー処理
}
try? FileManager.default.removeItem(atPath: path)
try! FileManager.default.removeItem(atPath: path)