c++ - Throw Exception in Bison and catch in main() -
is possibile throw exception in .y file , catch in .l yyparse() launched?
let's write example code. part of .y file:
%{ #include <stdio.h> #include <string> #include <cstring> using namespace std; extern int yylex(); extern void yyerror(char*); typedef enum { zero_division = 0, var_duplicate_name = 1, ... general = 100 } e_errors; const char* e_errnames[] = {"zero_division","var_duplicate_name",...,"general"}; ... %} //symbols %union { ... }; %token ... %start x1 %% x1: begin .... end ; { ... if(mycheck(i)>=0) throw var_duplicate_name; ... } ; ... %%
and how i'm trying catch var_duplicate_name in wrong way in .l file:
%{ #include <string.h> #include "proxydata.tab.h" void yyerror(char*); int yyparse(void); char linebuf[500]; //for output row in case of syntax error %} %option yylineno blanks [ \t\n]+ text [a-za-z0-9]+|[0-9]+.[0-9]+ %% \n.* { /* saving next row in case of syntax error */ strncpy(linebuf, yytext+1, sizeof(linebuf)); /* save next line */ yyless(1); /* give \n rescan */ } {blanks} { /* ignore */ }; ... return(...); {text} { yylval.str_val=(char*)strdup(yytext); return(identifier); } . return yytext[0]; %% void yyerror(char *s){ printf("line %d: %s @ %s in line:\n%s\n", yylineno, s, yytext, linebuf); } int yywrap (void){ ; } int main(int num_args, char** args){ if(num_args != 2) {printf("usage: ./parser filename\n"); exit(0);} file* file = fopen(args[1],"r"); if(file == null) {printf("couldn't open %s\n",args[1]); exit(0);} yyin = file; try{ yyparse(); }catch(int err){ printf("error! %s",e_errnames[err]); } fclose(file); }
in way, parser correctly created, when i'm giving in input file generates exception, face following message:
terminate called after throwing instance of 'e_errors' aborted (core dumped)
i know before writing printf("error! %s",e_errnames[err])
, should declare. extern const char* e_errnames[];
enough on top of flex file?
you should call yyerror()
or yy_abort designers intended. parsers shouldn't throw exceptions unless malfunction. , don't want 1 error parse, want them all.
nb you're not catching error in flex. you're catching in main()
, can anywhere. yyparse()
calls yylex()
, not other way round. thrown yyparse()
caught in main()
or whatever else supply call it, not in yylex()
.
Comments
Post a Comment