初步实现异常捕获机制
This commit is contained in:
97
soft/exception.c
Normal file
97
soft/exception.c
Normal file
@@ -0,0 +1,97 @@
|
||||
|
||||
|
||||
#include "setjmp.h"
|
||||
#include "stdio.h"
|
||||
#include "stdlib.h"
|
||||
#include "unistd.h"
|
||||
#include "string.h"
|
||||
#include "stdarg.h"
|
||||
#include "exception.h"
|
||||
#include "mystdlib.h"
|
||||
|
||||
|
||||
|
||||
exception_def *exception(){
|
||||
static exception_def frame={0};
|
||||
return &frame;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
void __throw(char *file,int line,const char *fmt,...){
|
||||
exception_def *f=exception();
|
||||
jmp_fram *h=f->jmp_head;
|
||||
char *buff=0;
|
||||
int length=0;
|
||||
va_list args;
|
||||
f->file=file;
|
||||
f->line=line;
|
||||
buff=f->log;
|
||||
va_start(args, fmt);
|
||||
length += vsnprintf(buff + length, THROW_LOG__MAX_SIZE - length - 1, fmt, args);
|
||||
va_end(args);
|
||||
longjmp((h->fram),1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
char *err_(){
|
||||
exception_def *f=exception();
|
||||
return f->log;
|
||||
}
|
||||
char *file_(){
|
||||
exception_def *f=exception();
|
||||
return f->file;
|
||||
}
|
||||
int line_(){
|
||||
exception_def *f=exception();
|
||||
return f->line;
|
||||
}
|
||||
void func_two();
|
||||
|
||||
int test_add(int a, int b)
|
||||
{
|
||||
printf("setjmp test.\n");
|
||||
try_{
|
||||
printf("first enter setjmp.\n");
|
||||
|
||||
try_{
|
||||
printf("try in try.\n");
|
||||
func_two();
|
||||
// throw_("throw two err.");
|
||||
}catch_{
|
||||
printf("file=%s,line=%d,err=%s.\n",file_(),line_(),err_());
|
||||
}
|
||||
throw_("throw a err.");
|
||||
|
||||
}catch_{
|
||||
printf("sssss\n");
|
||||
printf("file=%s,line=%d,err=%s.\n",file_(),line_(),err_());
|
||||
try_{
|
||||
printf("try in catch.\n");
|
||||
func_two();
|
||||
// throw_("throw two err.");
|
||||
}catch_{
|
||||
printf("file=%s,line=%d,err=%s.\n",file_(),line_(),err_());
|
||||
}
|
||||
}
|
||||
printf("setjmp end.\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
void func_two(){
|
||||
printf("in func:%s\n",__func__);
|
||||
void *p=mem_malloc(512);
|
||||
throw_("throw in func_two. in func:%s",__func__);
|
||||
mem_free(p);
|
||||
}
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user