adsense


Thursday, 26 November 2015

C++ LANGUAGE CATCHING EXCEPTION

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE CATCHING EXCEPTION






Catching Exceptions 


The catch block following the try block catches any exception. 
You can specify what type of exception you want to catch and 
this is determined by the exception declaration that appears 
in parentheses following the keyword catch. 

try 
{ 
   // protected code 
}catch( ExceptionName e ) 
{ 
  // code to handle ExceptionName exception 
} 
Above code will catch an exception of ExceptionName type. 
If you want to specify that a catch block should handle 
any type of exception that is thrown in a try block, 
you must put an ellipsis, ..., between the parentheses 
enclosing the exception declaration as follows: 

try 
{ 
   // protected code 
}catch(...) 
{ 
  // code to handle any exception 
} 
The following is an example, which throws a division 
by zero exception and we catch it in catch block. 

#include <iostream> 
using namespace std; 
 
double division(int a, int b) 
{ 
   if( b == 0 ) 
   { 
      throw "Division by zero condition!"; 
   } 
   return (a/b); 
} 
 
int main () 
{ 
   int x = 50; 
   int y = 0; 
   double z = 0; 
  
   try { 
     z = division(x, y); 
     cout << z << endl; 
   }catch (const char* msg) { 
     cerr << msg << endl; 
   } 
 
   return 0; 
} 

Because we are raising an exception of type const char*, 
so while catching this exception, we have to use const 
char* in catch block. If we compile and run above code, 
this would produce the following result: 

Division by zero condition! 


No comments: