UncaughtExceptionHandler.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface UncaughtExceptionHandler : NSObject

@end

void UncaughtExceptionHandlerStart(void);

NS_ASSUME_NONNULL_END

UncaughtExceptionHandler.m

#import "UncaughtExceptionHandler.h"
#import <UIKit/UIKit.h>
#import <libkern/OSAtomic.h>
#import <execinfo.h> NSString * const UncaughtExceptionHandlerSignalExceptionName = @"UncaughtExceptionHandlerSignalExceptionName";
NSString * const UncaughtExceptionHandlerSignalKey = @"UncaughtExceptionHandlerSignalKey";
NSString * const UncaughtExceptionHandlerAddressesKey = @"UncaughtExceptionHandlerAddressesKey"; volatile int32_t UncaughtExceptionCount = ;
const int32_t UncaughtExceptionMaximum = ; const NSInteger UncaughtExceptionHandlerSkipAddressCount = ;
const NSInteger UncaughtExceptionHandlerReportAddressCount = ; @interface UncaughtExceptionHandler ()
{
BOOL dismissed;
}
@end @implementation UncaughtExceptionHandler + (NSArray *)backtrace
{
void *callstack[];
int frames = backtrace(callstack, );
char **strs = backtrace_symbols(callstack, frames); NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
int end = UncaughtExceptionHandlerSkipAddressCount + UncaughtExceptionHandlerReportAddressCount; for (int i = UncaughtExceptionHandlerSkipAddressCount;i < end;i++)
{
[backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
}
free(strs); return backtrace;
} - (void)handleException:(NSException *)exception
{
NSString *reason = [exception reason];
NSString *addresses = [[exception userInfo] objectForKey:UncaughtExceptionHandlerAddressesKey];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
message:[NSString stringWithFormat:@"reason:%@\n addresses:%@",reason,addresses]
delegate:self
cancelButtonTitle:@"退出"
otherButtonTitles:@"继续", nil];
[alert show]; CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop); while (!dismissed)
{
for (NSString *mode in (__bridge NSArray *)allModes)
{
CFRunLoopRunInMode((CFStringRef)mode, 0.001, false);
}
} CFRelease(allModes); NSSetUncaughtExceptionHandler(NULL);
signal(SIGABRT, SIG_DFL);
signal(SIGILL, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGFPE, SIG_DFL);
signal(SIGBUS, SIG_DFL);
signal(SIGPIPE, SIG_DFL); if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName])
{
kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]);
}else{
[exception raise];
}
} - (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex
{
if (anIndex == )
{
dismissed = YES;
}
} @end void HandleException(NSException *exception);
void SignalHandler(int signal); void UncaughtExceptionHandlerStart(void)
{
NSSetUncaughtExceptionHandler(&HandleException);
signal(SIGABRT, SignalHandler);
signal(SIGILL, SignalHandler);
signal(SIGSEGV, SignalHandler);
signal(SIGFPE, SignalHandler);
signal(SIGBUS, SignalHandler);
signal(SIGPIPE, SignalHandler);
} void HandleException(NSException *exception)
{
int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);
if (exceptionCount > UncaughtExceptionMaximum)
{
return;
} NSArray *callStack = [UncaughtExceptionHandler backtrace];
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]];
[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey]; [[[UncaughtExceptionHandler alloc] init] performSelectorOnMainThread:@selector(handleException:)
withObject:[NSException exceptionWithName:[exception name] reason:[exception reason] userInfo:userInfo]
waitUntilDone:YES];
} void SignalHandler(int signal)
{
int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);
if (exceptionCount > UncaughtExceptionMaximum)
{
return;
} NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:signal] forKey:UncaughtExceptionHandlerSignalKey]; NSArray *callStack = [UncaughtExceptionHandler backtrace];
[userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey]; [[[UncaughtExceptionHandler alloc] init] performSelectorOnMainThread:@selector(handleException:)
withObject:[NSException exceptionWithName:UncaughtExceptionHandlerSignalExceptionName
reason:[NSString stringWithFormat:@"Signal %d was raised.",signal]
userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:signal]
forKey:UncaughtExceptionHandlerSignalKey]]
waitUntilDone:YES];
}

开启异常捕捉

#import "AppDelegate.h"
#import "UncaughtExceptionHandler.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch. UncaughtExceptionHandlerStart(); return YES;
}

异常示例

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSArray *array = @[@""];
NSLog(@"%@",array[]);
}

运行效果

[iOS]异常捕捉的更多相关文章

  1. iOS异常捕获

    文章目录 一. 系统Crash 二. 处理signal 下面是一些信号说明 关键点注意 三. 实战 四. Crash Callstack分析 – 进⼀一步分析 五. demo地址 六. 参考文献 前言 ...

  2. iOS异常采用处理方式

    iOS开发过程中我们经常会遇到异常问题 对异常的处理一般采用打印或者直接抛出.这样可以很方便我们调试过程有所参考,而且方便我们查看异常产生的位置信息 NSError(错误信息) 采用NSError的情 ...

  3. 基础知识《十》java 异常捕捉 ( try catch finally ) 你真的掌握了吗?

    本文转载自  java 异常捕捉 ( try catch finally ) 你真的掌握了吗? 前言:java 中的异常处理机制你真的理解了吗?掌握了吗?catch 体里遇到 return 是怎么处理 ...

  4. Java多线程——<七>多线程的异常捕捉

    一.概述 为什么要单独讲多线程的异常捕捉呢?先看个例子: public class ThreadException implements Runnable{ @Override public void ...

  5. Oracle- 存储过程和异常捕捉

    这段时间晚上有时候去打打球,回家看看电视剧,日子一天天过…….学了点ORACLE存储过程基础,作一下备注,以便日后需查阅. 创建无参存储过程 create procedure p_myPro1 is ...

  6. php错误及异常捕捉

    原文:php错误及异常捕捉 在实际开发中,错误及异常捕捉仅仅靠try{}catch()是远远不够的. 所以引用以下几中函数. a)   set_error_handler 一般用于捕捉  E_NOTI ...

  7. android中全局异常捕捉

    android中全局异常捕捉 只要写代码就会有bug,但是我们要想办法收集到客户的bug.有第三方bugly或者友盟等可以收集.但是,android原生就提供了有关收集异常的api,所以我们来学习一下 ...

  8. Spring 全局异常捕捉

    Spring全局异常捕捉类 注解@ControllerAdvice package com.sicdt.sicsign.web.bill.controller; import org.springfr ...

  9. 5.全局异常捕捉【从零开始学Spring Boot】

    在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 新建一个类GlobalDefaultExceptionHandler, 在class注解上@ControllerAdvice ...

随机推荐

  1. 在生产环境中安全执行更新删除SQL脚本的技巧

    今天在生产环境上解决问题,由于广发银行的管理制度是开发公司是不允许确生产环境的,所以我们只能把要更新的语句发给运营中心,由运营中心的投产人员执行,我们则在旁边看着:在他执行的时候发现了一个很有趣的技巧 ...

  2. Linux 网络流量查看 Linux ip traffic monitor

    Network monitoring on Linux This post mentions some linux command line tools that can be used to mon ...

  3. PHP自定义函数&数组

    <?php//生成随机数 和 时间函数//echo rand();//echo "<br>";//echo rand(0,10);//echo time();// ...

  4. Django 开启显示查询语句log

    # 下面语句加到setti中 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': ...

  5. web开发中的MVC框架与django框架的MTV模式

    1.MVC 有一种程序设计模式叫MVC,核心思想:分层,解耦,分离了 数据处理 和 界面显示 的代码,使得一方代码修改了不会影响到另外一方,提高了程序的可扩展性和可维护性. MVC的全拼为Model- ...

  6. Oracle EBS PO 接受入库

  7. C# 判断程序是否已经在运行

    方式1: /// <summary> /// 应用程序的主入口点. /// </summary> [STAThread] static void Main() { //获取欲启 ...

  8. [翻译] TCBlobDownload

    TCBlobDownload TCBlobDownload uses NSOperations to download large files (typically videos, music... ...

  9. [UI] 精美UI界面欣赏[9]

    精美UI界面欣赏[9]

  10. 【转载】 C语言命令行小猪佩奇

    // ASCII Peppa Pig by Milo Yip #include <math.h> #include <stdio.h> #include <stdlib. ...