adsense


Thursday, 26 November 2015

C++ LANGUAGE DEFINE NEW EXCEPTION

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



C++ LANGUAGE DEFINE NEW EXCEPTION





Define New Exceptions 


You can define your own exceptions by inheriting and 
overriding exception class functionality. Following 
is the example, which shows how you can use 
std::exception class to implement your own 
exception in standard way: 


#include <iostream> 

#include <exception> 

using namespace std; 
 
struct MyException : public exception 
{ 
  const char * what () const throw () 
  { 
    return "C++ Exception"; 
  } 
}; 
  
int main() 
{ 
  try 
  { 
    throw MyException(); 
  } 
  catch(MyException& e) 
  { 
    std::cout << "MyException caught" << std::endl; 
    std::cout << e.what() << std::endl; 
  } 
  catch(std::exception& e) 
  { 
    //Other errors 
  } 
} 

This would produce the following result: 

MyException caught 

C++ Exception 

Here, what() is a public method provided by exception 
class and it has been overridden by all the child 
exception classes. This returns the cause of an exception. 



No comments: