Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Created October 13, 2012 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chunkyguy/3883779 to your computer and use it in GitHub Desktop.
Save chunkyguy/3883779 to your computer and use it in GitHub Desktop.
Exception Handling C vs C++
/*
What: Exception using throw and jmp/longjmp
Author: Sid
Note: Test run with 3 cases
1: x(10), y(2) : Returns 2
2: x(10), y(0) : Catch exception DIVIDE_EXCP, prints error and quit
3: x(10), y(-2) : Catch exception NEG_EXCP, does nothing
*/
#include <iostream>
#include <csetjmp>
//Catch this exception
#define DIVIDE_EXCP 1
//Don't catch this
#define NEG_EXCP 2
//Using throw
double divide(const double &x, const double &y){
if(y == 0){
throw DIVIDE_EXCP;
}else if(y < 0){
throw NEG_EXCP;
}
return x/y;
}
void newway(const double &x, const double &y){
try{
std::cout << "NEW: " << divide(x, y) << std::endl;
}catch(int catch_excp){
if(catch_excp == DIVIDE_EXCP){
std::cout << "NEW: Divide by zero not allowed" << std::endl;
}else{
std::cout << "NEW: Uncaught exception" << std::endl;
}
}
}
//Using the setjmp/longjmp way
double divide(const double &x, const double &y, jmp_buf env){
if(y == 0){
longjmp(env, DIVIDE_EXCP);
}else if(y < 0){
longjmp(env, NEG_EXCP);
}
return x/y;
}
void oldway(const double &x, const double &y){
jmp_buf env;
int catch_excp = setjmp(env);
if(catch_excp == 0){
std::cout << "OLD: " << divide(x, y, env) << std::endl;
}else if(catch_excp == DIVIDE_EXCP){
std::cout << "OLD: Divide by zero not allowed" << std::endl;
return;
}else{
std::cout << "OLD: Uncaught exception" << std::endl;
}
}
int main(int argc, char **argv){
if(argc != 3){
std::cout << "Usage: " << argv[0] << " x y" << std::endl;
return 0;
}
double x = atof(argv[1]);
double y = atof(argv[2]);
oldway(x, y);
newway(x, y);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment