エラー処理
エラーハンドリングの練習のために書き残しておきます。下記のUIButtonをクリックすると、エラーハンドリング処理が実行されるアプリです。引数に文字列を取り、その文字列でエラーを判定します。

想定されるエラーをenmuで定義する
enum TestError:Error {
case Error1(String)
case Error2(String)
case Error3(String)
case AnotherError(String)
}
実行する関数を定義する
func TestMethod(str:String) throws {
if str == "error1" {
throw TestError.Error1("エラー発生1")
}else if str == "error2" {
throw TestError.Error2("エラー発生2")
}else if str == "error3" {
throw TestError.Error3("エラー発生3")
}else{
throw TestError.AnotherError("それ以外のエラー発生")
}
}
}
step3 実行する
do {
try TestMethod(str: "error3")
} catch TestError.Error1 (let err) {
print (err)
} catch TestError.Error2 (let err) {
print (err)
}catch TestError.Error3 (let err) {
print (err)
}catch TestError.AnotherError (let err) {
print (err)
}catch{
print("何かがおかしい")
}
実装
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func ErrHandlingTestButton(_ sender: Any) {
do {
try TestMethod(str: "error3")
} catch TestError.Error1 (let err) {
print (err)
} catch TestError.Error2 (let err) {
print (err)
}catch TestError.Error3 (let err) {
print (err)
}catch TestError.AnotherError (let err) {
print (err)
}catch{
print("何かがおかしい")
}
}
enum TestError:Error {
case Error1(String)
case Error2(String)
case Error3(String)
case AnotherError(String)
}
func TestMethod(str:String) throws {
if str == "error1" {
throw TestError.Error1("エラー発生1")
}else if str == "error2" {
throw TestError.Error2("エラー発生2")
}else if str == "error3" {
throw TestError.Error3("エラー発生3")
}else{
throw TestError.AnotherError("それ以外のエラー発生")
}
}
}
参考
Swift,Objective-Cプログラミング ~ iOS ~
【Swift3.0】Errorプロトコルを使った例外処理のサンプルを作ってみた
SwiftでのError Handlingを学び直す!byYutaka