signal 13 was raisedRaisedException 什么时候会抛这个异常

object_c2.0(29)
Mac osX(24)
应用异常崩溃是很正常的事情,但是应用异常崩溃信息对开发者非常重要。下面就介绍如何在iOS应用中捕获异常崩溃信息:
1. 程序启动中添加异常捕获监听函数,用来获取异常信息
& NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
& 官方文档介绍:Sets the top-level error-handling function where you can perform last-minute logging before the program terminates.
& UncaughtExceptionHandler是一个函数指针类型,所指向的函数需要我们实现,可以取自己想要的名字。当程序发生异常崩溃时,该函数会得到调用,这跟C,C++中的回调函数的概念是一样的。
2. 实现自己的处理函数
void UncaughtExceptionHandler(NSException *exception) {
& & NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
& & NSString *reason = [exception reason];//非常重要,就是崩溃的原因
& & NSString *name = [exception name];//异常类型
& & NSLog(@&exception type : %@ \n crash reason : %@ \n call stack info : %@&, name, reason, arr);
& &添加异常捕获监听函数,只能监听NSException类型的异常。eg:
& & NSDictionary *userInfo = [[NSDictionary alloc]initWithObjectsAndKeys:@&info1&, @&key1&, nil];
& & NSException *exception = [[NSException alloc]initWithName:@&自定义异常& reason:@&自定义异常原因& userInfo:userInfo];
而引起崩溃的大多数原因如:内存访问错误,重复释放等错误就无能为力了。因为这种错误它抛出的是Signal,所以必须要专门做Signal处理, 可以参考如下封装;测试时,可以调用abort()函数,模拟发送SIGABRT信号,不要联机测试,要脱机测试。
// &MQLSignalHandler.h
// &WebViewJS
// &Created by MQL on 16/4/23.
// &Copyright (C) 2016年 MQL. All rights reserved.
#import &Foundation/Foundation.h&
#include &sys/signal.h&
@interface MQLSignalHandler : NSObject
&* &信号处理器单例获取
&* &@return 信号处理器单例
+ (instancetype)
&* &处理异常用到的方法
&* &@param exception 自己封装的异常对象
- (void)handleExceptionTranslatedFromSignal:(NSException *)
// &MQLSignalHandler.m
// &WebViewJS
// &Created by MQL on 16/4/23.
// &Copyright (C) 2016年 MQL. All rights reserved.
#import &MQLSignalHandler.h&
#import &UIKit/UIKit.h&
#include &libkern/OSAtomic.h&
#include &execinfo.h&
//当前处理的异常个数
volatile int32_t UncaughtExceptionCount = 0;
//最大能够处理的异常个数
volatile int32_t UncaughtExceptionMaximum = 10;
&* &捕获信号后的回调函数
&* &@param signo 信号变量
void callbackHandlerOfCatchedSignal(int signo)
& & int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);
& & if (exceptionCount & UncaughtExceptionMaximum)
& & NSMutableDictionary *userInfo =[NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:signo] forKey:@&signal&];
& & //创建一个OC异常对象
& & NSException *ex = [NSException exceptionWithName:@&SignalExceptionName& reason:[NSString stringWithFormat:@&Signal %d was raised.\n&,signo] userInfo:userInfo];
& & //处理异常消息
& & [[MQLSignalHandler instance] performSelectorOnMainThread:@selector(handleExceptionTranslatedFromSignal:) withObject:ex waitUntilDone:YES];
@interface MQLSignalHandler ()
@property BOOL isD
&* &注册信号处理器
- (void)registerSignalH
@implementation MQLSignalHandler
&* &信号处理器单例获取
&* &@return 信号处理器单例
+ (instancetype)instance{
& & static dispatch_once_t onceT
& & static &MQLSignalHandler *s_SignalHandler = &
& & dispatch_once(&onceToken, ^{
& & & & if (s_SignalHandler == nil) {
& & & & & & s_SignalHandler &= &[[MQLSignalHandler alloc] init];
& & & & & & [s_SignalHandler registerSignalHandler];
& & return s_SignalH
&* &注册信号处理器
- (void)registerSignalHandler
& & //注册程序由于abort()函数调用发生的程序中止信号
& & signal(SIGABRT, callbackHandlerOfCatchedSignal);
& & //注册程序由于非法指令产生的程序中止信号
& & signal(SIGILL, callbackHandlerOfCatchedSignal);
& & //注册程序由于无效内存的引用导致的程序中止信号
& & signal(SIGSEGV, callbackHandlerOfCatchedSignal);
& & //注册程序由于浮点数异常导致的程序中止信号
& & signal(SIGFPE, callbackHandlerOfCatchedSignal);
& & //注册程序由于内存地址未对齐导致的程序中止信号
& & signal(SIGBUS, callbackHandlerOfCatchedSignal);
& & //程序通过端口发送消息失败导致的程序中止信号
& & signal(SIGPIPE, callbackHandlerOfCatchedSignal);
//处理异常用到的方法
- (void)handleExceptionTranslatedFromSignal:(NSException *)exception
& & CFRunLoopRef runLoop = CFRunLoopGetCurrent();
& & CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
& & UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@&程序出现问题啦& message:@&崩溃信息& delegate:self cancelButtonTitle:@&Cancel& otherButtonTitles:nil];
& & [alertView show];
& & //当接收到异常处理消息时,让程序开始runloop,防止程序死亡
& & while (!_isDismissed) {
& & & & for (NSString *mode in (__bridge NSArray *)allModes)
& & & & & & CFRunLoopRunInMode((CFStringRef)mode, 0, true);
& & //当点击弹出视图的Cancel按钮哦,isDimissed = YES,上边的循环跳出
& & CFRelease(allModes);
& & //拦截处理后,执行默认处理
& & signal(SIGABRT, SIG_DFL);
& & signal(SIGILL, SIG_DFL);
& & signal(SIGSEGV, SIG_DFL);
& & signal(SIGFPE, SIG_DFL);
& & signal(SIGBUS, SIG_DFL);
& & signal(SIGPIPE, SIG_DFL);
- (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex
& & //因为这个弹出视图只有一个Cancel按钮,所以直接进行修改isDimsmissed这个变量了
& & _isDismissed = YES;
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
(3)(11)(1)(2)(1)(2)(3)(3)(13)(1)(3)(2)(2)(1)trackbacks-0
demo地址:/easonoutlook/UncaughtExceptionHandler
IOS SDK中提供了一个现成的函数 NSSetUncaughtExceptionHandler 用来做异常处理,但功能非常有限,而引起崩溃的大多数原因如:内存访问错误,重复释放等错误就无能为力了,因为这种错误它抛出的是Signal,所以必须要专门做Signal处理。首先定义一个UncaughtExceptionHandler类,.h头文件的代码如下:
#import &UIKit/UIKit.h&
@interface UncaughtExceptionHandler : NSObject
void InstallUncaughtExceptionHandler();
然后在.mm文件实现InstallUncaughtExceptionHandler(),如下:
void InstallUncaughtExceptionHandler()
signal(SIGABRT, MySignalHandler);
signal(SIGILL, MySignalHandler);
signal(SIGSEGV, MySignalHandler);
signal(SIGFPE, MySignalHandler);
signal(SIGBUS, MySignalHandler);
signal(SIGPIPE, MySignalHandler);
这样,当应用发生错误而产生上述Signal后,就将会进入我们自定义的回调函数MySignalHandler。为了得到崩溃时的现场信息,还可以加入一些获取CallTrace及设备信息的代码,.mm文件的完整代码如下:
#import "UncaughtExceptionHandler.h"
#include &libkern/OSAtomic.h&
#include &execinfo.h&
NSString * const UncaughtExceptionHandlerSignalExceptionName = @"UncaughtExceptionHandlerSignalExceptionName";
NSString * const UncaughtExceptionHandlerSignalKey = @"UncaughtExceptionHandlerSignalKey";
NSString * const UncaughtExceptionHandlerAddressesKey = @"UncaughtExceptionHandlerAddressesKey";
volatile int32_t UncaughtExceptionCount = 0;
const int32_t UncaughtExceptionMaximum = 10;
const NSInteger UncaughtExceptionHandlerSkipAddressCount = 4;
const NSInteger UncaughtExceptionHandlerReportAddressCount = 5;
@implementation UncaughtExceptionHandler
+ (NSArray *)backtrace
& & & & void* callstack[128];
&int frames = backtrace(callstack, 128);
&char **strs = backtrace_symbols(callstack, frames);&
&NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
&i = UncaughtExceptionHandlerSkipAddressC
&i & UncaughtExceptionHandlerSkipAddressCount +
UncaughtExceptionHandlerReportAddressC
&[backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
&free(strs);&
- (void)alertView:(UIAlertView *)anAlertView clickedButtonAtIndex:(NSInteger)anIndex
if (anIndex == 0)
dismissed = YES;
- (void)handleException:(NSException *)exception
UIAlertView *alert =
[[[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Unhandled exception", nil)
message:[NSString stringWithFormat:NSLocalizedString(
@"You can try to continue but the application may be unstable.\n"
@"%@\n%@", nil),
[exception reason],
[[exception userInfo] objectForKey:UncaughtExceptionHandlerAddressesKey]]
delegate:self
cancelButtonTitle:NSLocalizedString(@"Quit", nil)
otherButtonTitles:NSLocalizedString(@"Continue", nil), nil]
autorelease];
[alert show];
CFRunLoopRef runLoop = CFRunLoopGetCurrent();
CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop);
while (!dismissed)
for (NSString *mode in (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]);
[exception raise];
NSString* getAppInfo()
& & NSString *appInfo = [NSString stringWithFormat:@"App : %@ %@(%@)\nDevice : %@\nOS Version : %@ %@\nUDID : %@\n",
& & & & & & & & & & & & & [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"],
& & & & & & & & & & & & & [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"],
& & & & & & & & & & & & & [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],
& & & & & & & & & & & & & [UIDevice currentDevice].model,
& & & & & & & & & & & & & [UIDevice currentDevice].systemName,
& & & & & & & & & & & & & [UIDevice currentDevice].systemVersion,
& & & & & & & & & & & & & [UIDevice currentDevice].uniqueIdentifier];
& & NSLog(@"Crash!!!! %@", appInfo);
& & return appI
void MySignalHandler(int signal)
int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount);
if (exceptionCount & UncaughtExceptionMaximum)
NSMutableDictionary *userInfo =
[NSMutableDictionary
dictionaryWithObject:[NSNumber numberWithInt:signal]
forKey:UncaughtExceptionHandlerSignalKey];
NSArray *callStack = [UncaughtExceptionHandler backtrace];
setObject:callStack
forKey:UncaughtExceptionHandlerAddressesKey];
[[[[UncaughtExceptionHandler alloc] init] autorelease]
performSelectorOnMainThread:@selector(handleException:)
withObject:
[NSException
exceptionWithName:UncaughtExceptionHandlerSignalExceptionName
[NSString stringWithFormat:
NSLocalizedString(@"Signal %d was raised.\n"
& & & & & & & & & & & & & & & & & & & & & @"%@", nil),
signal, getAppInfo()]
[NSDictionary
dictionaryWithObject:[NSNumber numberWithInt:signal]
forKey:UncaughtExceptionHandlerSignalKey]]
waitUntilDone:YES];
void InstallUncaughtExceptionHandler()
signal(SIGABRT, MySignalHandler);
signal(SIGILL, MySignalHandler);
signal(SIGSEGV, MySignalHandler);
signal(SIGFPE, MySignalHandler);
signal(SIGBUS, MySignalHandler);
signal(SIGPIPE, MySignalHandler);
在应用自身的 didFinishLaunchingWithOptions 前,加入一个函数:
- (void)installUncaughtExceptionHandler
InstallUncaughtExceptionHandler();
最后,在 didFinishLaunchingWithOptions 中加入这一句代码就行了:
[self InstallUncaughtExceptionHandler];
现在,基本上所有崩溃都能Hold住了。崩溃时将会显示出如下的对话框:
这样在崩溃时还能从容地弹出对话框,比起闪退来,用户也不会觉得那么不爽。然后在下次启动时还可以通过邮件来发送Crash文件到邮箱,这就看各个应用的需求了。
阅读(...) 评论()zhangxingnan 的BLOG
用户名:zhangxingnan
文章数:42
访问量:3918
注册日期:
阅读量:5863
阅读量:12276
阅读量:308778
阅读量:1025201
51CTO推荐博文
SignalDescriptionSignal number on Linux x86[1]SIGABRTProcess aborted6SIGALRMSignal raised by alarm14SIGBUSBus error: "access to undefined portion of memory object"7SIGCHLDChild process terminated, stopped (or continued*)17SIGCONTContinue if stopped18SIGFPEFloating point exception: "erroneous arithmetic operation"8SIGHUPHangup1SIGILLIllegal instruction4SIGINTInterrupt2SIGKILLKill (terminate immediately)9SIGPIPEWrite to pipe with no one reading13SIGQUITQuit and dump core3SIGSEGVSegmentation violation11SIGSTOPStop executing temporarily19SIGTERMTermination (request to terminate)15SIGTSTPTerminal stop signal20SIGTTINBackground process attempting to read from tty ("in")21SIGTTOUBackground process attempting to write to tty ("out")22SIGUSR1User-defined 110SIGUSR2User-defined 212SIGPOLLPollable event29SIGPROFProfiling timer expired27SIGSYSBad syscall31SIGTRAPTrace/breakpoint trap5SIGURGUrgent data available on socket23SIGVTALRMSignal raised by timer counting virtual time: "virtual timer expired"26SIGXCPUCPU time limit exceeded24SIGXFSZFile size limit exceeded25本文出自 “” 博客,请务必保留此出处
了这篇文章
类别:┆阅读(0)┆评论(0)ios - Objective C, Thread 1 Program Received Signal SIGABRT - Stack Overflow
to customize your list.
Announcing Stack Overflow Documentation
We started with Q&A. Technical documentation is next, and we need your help.
Whether you're a beginner or an experienced developer, you can contribute.
This question already has an answer here:
54 answers
I am trying to compile and run a simple tutorial for an Objective C app using Interface Builder. I am using Xcode 4.0.2 and simulating on iOS (iPhone) 4.3
When I build the project, it builds alright but once the app tries to run it crashes with:
int main(int argc, char *argv[])
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, @"SimpleUIAppDelegate");
[pool release];
return retV
I get the error on line 4: int retVal = UI...
Thread 1: Program Received Signal "SIGABRT".
If the other files of this project need to be posted for clarity, I can do that.
SimpleUIViewController.h:
#import &UIKit/UIKit.h&
@interface SimpleUIViewController : UIViewController &UITextFieldDelegate& {
UITextField *textI
NSString *
@property (nonatomic, retain) IBOutlet UITextField *textI
@property (nonatomic, retain) IBOutlet UILabel *
@property (nonatomic, copy) NSString *
- (IBAction)changeGreeting:(id)
SimpleUIViewController.m:
#import "SimpleUIViewController.h"
@implementation SimpleUIViewController
@synthesize textI
- (IBAction)changeGreeting:(id)sender {
self.name = textInput.
NSString *nameString =
if([nameString length] == 0) {
nameString = @"Inigo Montoya";
NSString *greeting = [[NSString alloc]
initWithFormat:@"Hello, my name is %@!", nameString];
label.text =
[greeting release];
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if(theTextField == textInput) {
[textInput resignFirstResponder];
return YES;
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Release anything that's not essential, such as cached data
- (void)dealloc {
[textInput release];
[label release];
[name release];
[super dealloc];
Error message:
This GDB was configured as "x86_64-apple-darwin".Attaching to process 2668.
11:20:21.662 InterfaceBuilder[] Unknown class InterfaceBuilderAppDelegate_iPhone in Interface Builder file.
11:20:21.666 InterfaceBuilder[] *** Terminating app due to uncaught
exception 'NSUnknownKeyException', reason: '[&UIApplication 0x4b1a900&
setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key
textInput.'
*** Call stack at first throw:
CoreFoundation
0x00dc25a9 __exceptionPreprocess + 185
libobjc.A.dylib
0x00f16313 objc_exception_throw + 44
CoreFoundation
0x00dc24e1 -[NSException raise] + 17
Foundation
0x _NSSetUsingKeyValueSetter + 135
Foundation
0x -[NSObject(NSKeyValueCoding) setValue:forKey:] + 285
0x0021030c -[UIRuntimeOutletConnection connect] + 112
CoreFoundation
0x00d388cf -[NSArray makeObjectsPerformSelector:] + 239
0x0020ed23 -[UINib instantiateWithOwner:options:] + 1041
0x00210ab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
0x0001617a -[UIApplication _loadMainNibFile] + 172
0x00016cf4 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 291
0x -[UIApplication handleEvent:withNewEvent:] + 1533
0x00019abf -[UIApplication sendEvent:] + 71
0x0001ef2e _UIApplicationHandleEvent + 7576
GraphicsServices
0x00ffb992 PurpleEventCallback + 1550
CoreFoundation
0x00da3944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
CoreFoundation
0x00d03cf7 __CFRunLoopDoSource1 + 215
CoreFoundation
0x00d00f83 __CFRunLoopRun + 979
CoreFoundation
0x00d00840 CFRunLoopRunSpecific + 208
CoreFoundation
0x00d00761 CFRunLoopRunInMode + 97
0x -[UIApplication _run] + 623
0x00022c93 UIApplicationMain + 1160
InterfaceBuilder
0x000027ff main + 127
InterfaceBuilder
0x start + 53
terminate called after throwing an instance of 'NSException'
sharedlibrary apply-load-rules all
Current language: currently objective-c
Im new to obj-c, and have absolutely no idea what I'm looking at in regards to that error message. Any help?
7,21132655
4,86283576
marked as duplicate by
&objective-c badge can single-handedly close
questions as duplicates and reopen them as needed.
This question has been asked before and already has an answer. If those answers do not fully address your question, please .
You have an error in your NIB/XIB file.
It looks like you have previously attached an IBOutlet (textInput) and now the connection is broken. You should double check all connections in Interface Builder.
7,21132655
It's likely that you have set the type of 'File's Owner' incorrectly to UIViewController in your SimpleUIViewController's xib. Please set it to SimpleUIViewController in identity inspector pane.
Now I see it! Your crash report says:
Unknown class InterfaceBuilderAppDelegate_iPhone
So, it seems that you set your App Delegate in IB to this class, but this class is not available in your project. Check this. Either you misspelled the class name or you should add the relevant class to your project.
Highly likely, your text field is connected to this app delegate.
Have you connected your text field in Interface Builder to the SimpleUIViewController outlet?
Since it seems from the tutorial that you are not using MainWindow.xib, I would say that your project is missing running the proper delegate. Try making this change in your main:
int retVal = UIApplicationMain(argc, argv, nil, @"SimpleUIAppDelegate");
If my hypothesis is right, that should move your forward.
61.2k971105
To fix it, load the XIB in Interface Builder, select the File Inspector tab, and uncheck Use autolayout. Alternatively, you can target iOS 6.0+-only devices and change the minimum target, if you absolutely must have autolayout.
thread 1 program recived singal sigabrt
some times NSString value is goes to nill!
it may cause this while initialization of your application!
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabledClass: SignalException (Ruby 2.3.0)
Quicksearch
SignalException
Raised when a signal is received.
Process.kill('HUP',Process.pid)
rescue SignalException =& e
puts &received Exception #{e}&
received Exception SIGHUP
Construct a new
sig_name should be a known signal name.
static VALUE
esignal_init(int argc, VALUE *argv, VALUE self)
int argnum = 1;
VALUE sig = Q
const char *
if (argc & 0) {
sig = rb_check_to_integer(argv[0], &to_int&);
if (!NIL_P(sig)) argnum = 2;
else sig = argv[0];
rb_check_arity(argc, 1, argnum);
if (argnum == 2) {
signo = NUM2INT(sig);
if (signo & 0 || signo & NSIG) {
rb_raise(rb_eArgError, &invalid signal number (%d)&, signo);
if (argc & 1) {
sig = argv[1];
sig = rb_signo2signm(signo);
int len = sizeof(signame_prefix);
if (SYMBOL_P(sig)) sig = rb_sym2str(sig); else StringValue(sig);
signm = RSTRING_PTR(sig);
if (strncmp(signm, signame_prefix, len) == 0) {
signo = signm2signo(signm);
if (!signo) {
rb_raise(rb_eArgError, &unsupported name `%.*s%&PRIsVALUE&'&,
len, signame_prefix, sig);
sig = rb_sprintf(&SIG%s&, signm);
rb_call_super(1, &sig);
rb_ivar_set(self, id_signo, INT2NUM(signo));
Returns a signal number.
static VALUE
esignal_signo(VALUE self)
return rb_ivar_get(self, id_signo);
Please enable JavaScript to view the
Generated with Ruby-doc Rdoc Generator 0.34.6.

我要回帖

更多关于 signal 6 was raised 的文章

 

随机推荐