In both C++ and Java, programmers often create special classes for programmer-de
ID: 3843043 • Letter: I
Question
In both C++ and Java, programmers often create special classes for programmer-defined Exceptions. For example, for a project that is doing analysis of word occurrences on Subreddits of the site reddit.com, you might create a NoSuchSubreddit exception for the case where the program is trying to access a Subreddit that does not exist. In Java, if you want to look at the code and find out whether a particular class is being used as an exception, it is easy: you see whether it inherits from java.lang.Exception either directly or indirectly. In C++ what do you look for in the code to indicate whether a particular class is used as an exception?Explanation / Answer
Below is how we use particular class as an exception in C++ ( please rate ,if satisfied)
The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called std::exception and is defined in the <exception> header. This class has a virtual member function called what that returns a null-terminated character sequence (of type char *) and that can be overwritten in derived classes to contain some sort of description of the exception.
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
}
}
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.
So Search for the header <execption> and see if that class inherits exception class functionality.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.