iOS捕獲異常,常用的異常處理方法

2021-09-06 22:11:35 字數 4000 閱讀 9991

以下程式已測試並通過:

裝置:ios 8模擬器中

開發工具:xcode6.1

使用@try、catch捕獲異常:

以下是最簡單的**寫法,其中@finally可以去掉:

1

2

3

4

5

6

7

8

9

@try

@catch(n***ception *exception)

@finally

在這裡舉多一具比較詳細的方法,丟擲異常:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@try

@catch(n***ception *exception)

@finally

// 4

// 這裡一定會執行

nslog(@"try");

trytwo方法**:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

- (void)trytwo

@catch(n***ception *exception)

@finally

// 9

// 如果丟擲異常,那麼這段**則不會執行

nslog(@"如果這裡丟擲異常,那麼這段**則不會執行");

}

為了方便大家理解,我在這裡再說明一下情況:

如果6丟擲異常,那麼執行順序為:1->5->6->8->3->4

如果6沒丟擲異常,那麼執行順序為:1->5->7->8->9->3->4

2)部分情況的崩潰我們是無法避免的,就算是qq也會有崩潰的時候。因此我們可以在程式崩潰之前做一些「動作」(收集錯誤資訊),以下例子是把捕獲到的異常傳送至開發者的郵箱。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

nssetuncaughtexceptionhandler(&uncaughtexceptionhandler);

returnyes;

}

void uncaughtexceptionhandler(n***ception *exception) {

/**

*  獲取異常崩潰資訊

*/

nsarray *callstack = [exception callstacksymbols];

nsstring *reason = [exception reason];

nsstring *name = [exception name];

nsstring *content = [nsstring stringwithformat:@"*****===異常錯誤報告*****===\nname:%@\nreason:\n%@\ncallstacksymbols:\n%@",name,reason,[callstack componentsjoinedbystring:@"\n"]];

/**

*  把異常崩潰資訊傳送至開發者郵件

*/

nsmutablestring *mailurl = [nsmutablestring string];

"mailto:[email protected]"];

"?subject=程式異常崩潰,請配合傳送異常報告,謝謝合作!"];

"&body=%@", content];

// 開啟位址

nsstring *mailpath = [mailurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

IOS捕獲異常,常用的異常處理方法

以下是最簡單的 寫法,其中 finally可以去掉 try catch n ception exception finally 在這裡舉多一具比較詳細的方法,丟擲異常 try catch n ception exception finally 4 這裡一定會執行 nslog try trytwo方法...

iOS捕獲異常,常用的異常處理方法

以下程式已測試並通過 裝置 ios 8模擬器中 開發工具 xcode6.1 使用 try catch捕獲異常 以下是最簡單的 寫法,其中 finally可以去掉 1 2 3 4 5 6 7 8 9 try catch n ception exception finally 在這裡舉多一具比較詳細的方...

iOS常用捕獲異常及處理方法

使用 try catch捕獲異常 try catch n ception exception finally 有時候崩潰我們是無法避免的,因此我們可以在程式崩潰之前做一些 動作 收集錯誤資訊 下面的例子是把捕獲到的異常傳送至開發者的郵箱。來自garveycalvin的部落格 nssetuncaugh...