纯C语言有try功能吗?

forestzhu0823 2012-01-08 01:21:53
有段代码可能会引起错误,甚至程序崩溃,
但是又无检查手段,
想用类似try catch语句,
请问纯C语言有这样的功能吗?
...全文
1926 33 打赏 收藏 转发到动态 举报
写回复
用AI写文章
33 条回复
切换为时间正序
请发表友善的回复…
发表回复
wizard_tiger 2012-08-20
  • 打赏
  • 举报
回复
纯C中应该是没有的。
ForestDB 2012-08-20
  • 打赏
  • 举报
回复
没有,与其相信try,catch不如自己debug。
whucv 2012-08-19
  • 打赏
  • 举报
回复
标准C语言没有try catch,异常是C++增加的功能
Frog1228 2012-08-19
  • 打赏
  • 举报
回复
[Quote=引用 16 楼 的回复:]
写日志,断点

在世界上还没有异常处理之前,程序员依旧坚强存活着。
[/Quote]
但是C语言里,怎么判断它出错啊?
Frog1228 2012-08-19
  • 打赏
  • 举报
回复
[Quote=引用 16 楼 的回复:]
写日志,断点

在世界上还没有异常处理之前,程序员依旧坚强存活着。
[/Quote]
在C语言里写日志,这个日志怎么写啊?是猜想哪边可能出错,就把它出错的信息写到日志里?
东莞某某某 2012-08-19
  • 打赏
  • 举报
回复
windows SEH
project2502 2012-08-19
  • 打赏
  • 举报
回复
异常处理是操作系统提供的功能啊
小新娜不怕 2012-08-19
  • 打赏
  • 举报
回复
面向对象的C
jiandingzhe 2012-08-19
  • 打赏
  • 举报
回复
不知道为什么,就是不喜欢try...catch...模式。
C里面可以用longjmp,是标准库的一部分,不过有点丑陋。
赵4老师 2012-02-10
  • 打赏
  • 举报
回复
[Quote=引用 22 楼 mjjackey 的回复:]
引用 20 楼 r3000 的回复:
标准C语言没有try catch,异常是C++增加的功能,前些年某些大牛还讨论过C++的这个功能到底
是好还是不好。也许事物都有两面性吧,异常用不好是万恶的。

一般大规模C程序都是靠日志等手段的。

“一般大规模C程序都是靠日志等手段的。”怎么用?
[/Quote]
比如这样用
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <process.h>
#include <io.h>
//Log{
#define MAXLOGSIZE 10000000
#define ARRSIZE(x) (sizeof(x)/sizeof(x[0]))
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
char logstr[16000];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
void Lock(CRITICAL_SECTION *l) {
EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
LeaveCriticalSection(l);
}
void LogV(const char *pszFmt,va_list argp) {
struct tm *now;
struct timeb tb;

if (NULL==pszFmt||0==pszFmt[0]) return;
if (-1==_vsnprintf(logstr,ARRSIZE(logstr),pszFmt,argp)) logstr[ARRSIZE(logstr)-1]=0;
ftime(&tb);
now=localtime(&tb.time);
sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
sprintf(timestr,"%02d:%02d:%02d",now->tm_hour ,now->tm_min ,now->tm_sec );
sprintf(mss,"%03d",tb.millitm);
printf("%s %s.%s %s",datestr,timestr,mss,logstr);
flog=fopen(logfilename1,"a");
if (NULL!=flog) {
fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
if (ftell(flog)>MAXLOGSIZE) {
fclose(flog);
if (rename(logfilename1,logfilename2)) {
remove(logfilename2);
rename(logfilename1,logfilename2);
}
flog=fopen(logfilename1,"a");
if (NULL==flog) return;
}
fclose(flog);
}
}
void Log(const char *pszFmt,...) {
va_list argp;

Lock(&cs_log);
va_start(argp,pszFmt);
LogV(pszFmt,argp);
va_end(argp);
Unlock(&cs_log);
}
//Log}
#define ASIZE 200
#define BSIZE 240
#define CSIZE 2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
int head;
int tail;
int size;
char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
int i,j,k;
char binstr[80];

Lock(&cs_HEX);
for (i=0;i<len;i++) {
if (0==(i%16)) {
sprintf(binstr,"%03d %04x -",cn,i);
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
} else if (15==(i%16)) {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
sprintf(binstr,"%s ",binstr);
for (j=i-15;j<=i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
} else {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
}
}
if (0!=(i%16)) {
k=16-(i%16);
for (j=0;j<k;j++) {
sprintf(binstr,"%s ",binstr);
}
sprintf(binstr,"%s ",binstr);
k=16-k;
for (j=i-k;j<i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
}
Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;

lent=0;
Lock(cs);
if (fbuf->size>=len) {
lent=len;
if (fbuf->head+lent>BSIZE) {
len1=BSIZE-fbuf->head;
memcpy(buf ,fbuf->data+fbuf->head,len1);
len2=lent-len1;
memcpy(buf+len1,fbuf->data ,len2);
fbuf->head=len2;
} else {
memcpy(buf ,fbuf->data+fbuf->head,lent);
fbuf->head+=lent;
}
fbuf->size-=lent;
}
Unlock(cs);
return lent;
}
void thdB(void *pcn) {
char *recv_buf;
int recv_nbytes;
int cn;
int wc;
int pb;

cn=(int)pcn;
Log("%03d thdB thread begin...\n",cn);
while (1) {
Sleep(10);
recv_buf=(char *)Cbuf;
recv_nbytes=CSIZE;
wc=0;
while (1) {
pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
if (pb) {
Log("%03d recv %d bytes\n",cn,pb);
HexDump(cn,recv_buf,pb);
Sleep(1);
} else {
Sleep(1000);
}
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;

Lock(cs);
lent=len;
if (fbuf->size+lent>BSIZE) {
lent=BSIZE-fbuf->size;
}
if (fbuf->tail+lent>BSIZE) {
len1=BSIZE-fbuf->tail;
memcpy(fbuf->data+fbuf->tail,buf ,len1);
len2=lent-len1;
memcpy(fbuf->data ,buf+len1,len2);
fbuf->tail=len2;
} else {
memcpy(fbuf->data+fbuf->tail,buf ,lent);
fbuf->tail+=lent;
}
fbuf->size+=lent;
Unlock(cs);
return lent;
}
void thdA(void *pcn) {
char *send_buf;
int send_nbytes;
int cn;
int wc;
int a;
int pa;

cn=(int)pcn;
Log("%03d thdA thread begin...\n",cn);
a=0;
while (1) {
Sleep(100);
memset(Abuf,a,ASIZE);
a=(a+1)%256;
if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
send_buf=(char *)Abuf;
send_nbytes=ASIZE;
Log("%03d sending %d bytes\n",cn,send_nbytes);
HexDump(cn,send_buf,send_nbytes);
wc=0;
while (1) {
pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
Log("%03d sent %d bytes\n",cn,pa);
HexDump(cn,send_buf,pa);
send_buf+=pa;
send_nbytes-=pa;
if (send_nbytes<=0) break;//
Sleep(1000);
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int main() {
InitializeCriticalSection(&cs_log );
Log("Start===========================================================\n");
InitializeCriticalSection(&cs_HEX );
InitializeCriticalSection(&cs_BBB );

BBB.head=0;
BBB.tail=0;
BBB.size=0;

_beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
_beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);

if (!access("No_Loop",0)) {
remove("No_Loop");
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
while (1) {
Sleep(1000);
if (No_Loop) break;//
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
Sleep(3000);
DeleteCriticalSection(&cs_BBB );
DeleteCriticalSection(&cs_HEX );
Log("End=============================================================\n");
DeleteCriticalSection(&cs_log );
return 0;
}
赵4老师 2012-02-10
  • 打赏
  • 举报
回复
仅供参考
/* FPRESET.C: This program uses signal to set up a
* routine for handling floating-point errors.
*/

#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <string.h>

jmp_buf mark; /* Address for long jump to jump to */
int fperr; /* Global error number */

void __cdecl fphandler( int sig, int num ); /* Prototypes */
void fpcheck( void );

void main( void )
{
double n1, n2, r;
int jmpret;
/* Unmask all floating-point exceptions. */
_control87( 0, _MCW_EM );
/* Set up floating-point error handler. The compiler
* will generate a warning because it expects
* signal-handling functions to take only one argument.
*/
if( signal( SIGFPE, fphandler ) == SIG_ERR )

{
fprintf( stderr, "Couldn't set SIGFPE\n" );
abort(); }

/* Save stack environment for return in case of error. First
* time through, jmpret is 0, so true conditional is executed.
* If an error occurs, jmpret will be set to -1 and false
* conditional will be executed.
*/
jmpret = setjmp( mark );
if( jmpret == 0 )
{
printf( "Test for invalid operation - " );
printf( "enter two numbers: " );
scanf( "%lf %lf", &n1, &n2 );
r = n1 / n2;
/* This won't be reached if error occurs. */
printf( "\n\n%4.3g / %4.3g = %4.3g\n", n1, n2, r );

r = n1 * n2;
/* This won't be reached if error occurs. */
printf( "\n\n%4.3g * %4.3g = %4.3g\n", n1, n2, r );
}
else
fpcheck();
}
/* fphandler handles SIGFPE (floating-point error) interrupt. Note
* that this prototype accepts two arguments and that the
* prototype for signal in the run-time library expects a signal
* handler to have only one argument.
*
* The second argument in this signal handler allows processing of
* _FPE_INVALID, _FPE_OVERFLOW, _FPE_UNDERFLOW, and
* _FPE_ZERODIVIDE, all of which are Microsoft-specific symbols
* that augment the information provided by SIGFPE. The compiler
* will generate a warning, which is harmless and expected.

*/
void fphandler( int sig, int num )
{
/* Set global for outside check since we don't want
* to do I/O in the handler.
*/
fperr = num;
/* Initialize floating-point package. */
_fpreset();
/* Restore calling environment and jump back to setjmp. Return
* -1 so that setjmp will return false for conditional test.
*/
longjmp( mark, -1 );
}
void fpcheck( void )
{
char fpstr[30];
switch( fperr )
{
case _FPE_INVALID:
strcpy( fpstr, "Invalid number" );
break;
case _FPE_OVERFLOW:
strcpy( fpstr, "Overflow" );

break;
case _FPE_UNDERFLOW:
strcpy( fpstr, "Underflow" );
break;
case _FPE_ZERODIVIDE:
strcpy( fpstr, "Divide by zero" );
break;
default:
strcpy( fpstr, "Other floating point error" );
break;
}
printf( "Error %d: %s\n", fperr, fpstr );
}
//Output
//
//Test for invalid operation - enter two numbers: 5 0
//Error 131: Divide by zero
Frog1228 2012-02-10
  • 打赏
  • 举报
回复
[Quote=引用 20 楼 r3000 的回复:]
标准C语言没有try catch,异常是C++增加的功能,前些年某些大牛还讨论过C++的这个功能到底
是好还是不好。也许事物都有两面性吧,异常用不好是万恶的。

一般大规模C程序都是靠日志等手段的。
[/Quote]
“一般大规模C程序都是靠日志等手段的。”怎么用?
we_sky2008 2012-01-31
  • 打赏
  • 举报
回复
可是使用setjmp和longjmp模拟C++中的try和catch

#include<stdio.h>
#include<setjmp.h>
#include<stdlib.h>

#define try if (!(ret = setjmp(buf)))
#define catch(i) else
#define throw(i) longjmp(buf, i)

jmp_buf buf;

void sub1()
{
printf("in sub1()\n");
throw(1);
printf("you will never see this!");
}
void sub2()
{
printf("in sub2()\n");
throw(2);
printf("you will never see this!");
}
int main()
{
int ret;
try
{
printf("first time through\n");
sub1();
sub2();
}
catch(ret)
{
switch(ret)
{
case 1:
printf("sub1 raised an exception\n");
break;
case 2:
printf("sub2 raised an exception\n");
break;
default:
break;
}
}
printf("back in main()\n");
system("pause");
return 0;
}
程序员小迷 2012-01-31
  • 打赏
  • 举报
回复
有的;setjmp等等
Frog1228 2012-01-31
  • 打赏
  • 举报
回复
康斯坦汀 2012-01-31
  • 打赏
  • 举报
回复
标准C语言没有try catch,异常是C++增加的功能,前些年某些大牛还讨论过C++的这个功能到底
是好还是不好。也许事物都有两面性吧,异常用不好是万恶的。

一般大规模C程序都是靠日志等手段的。
jackyjkchen 2012-01-11
  • 打赏
  • 举报
回复
微软的结构化异常,Windows操作系统开发就用的这个
赵4老师 2012-01-11
  • 打赏
  • 举报
回复
谁说“程序崩溃,无检查手段”?

崩溃的时候在弹出的对话框按相应按钮进入调试,按Alt+7键查看Call Stack里面从上到下列出的对应从里层到外层的函数调用历史。双击某一行可将光标定位到此次调用的源代码或汇编指令处。

序员 2012-01-11
  • 打赏
  • 举报
回复
Negative。。。
bruceteen 2012-01-11
  • 打赏
  • 举报
回复
有段代码可能会引起错误,甚至程序崩溃
--- 即使C语言有try功能,也帮不了你。因为 try 不能捕获“错误”
try 捕获的是“异常”,“异常”是代码逻辑上的,在运行层面它是正常的
加载更多回复(13)

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧