Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c++ - What type of exception should I throw?

After going through some links on exception handling (1, 2, and 3), I know that C++ programs can throw pretty much anything as exceptions (int, char*, string, exception class). I know that std::exception is the base class for standard exceptions thrown by the program. However, I'm trying to design a try...catch block as such:

try
{
    MyFunc();
}
catch (certain exceptions)
{
    // deal with the exception accordingly
}
catch (the rest of the exceptions)
{
    // deal with these accordingly
}

while MyFunc() contains the following:

void MyFunc()
{
    ...
    if (certain condition is true) throw exception;
    ...
}

The trouble is that in that part of MyFunc function, I'm not sure what type of exception I should throw. To keep the code clean by implementing my own exceptions class, I have no idea what would be a good way to implement such exceptions class.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You would derive your own class from std::exception, so that there is some way of uniformly handling exceptions.

If this seems like overkill, you can throw std::logic_error or one of the other standard exception types intended for applications to use.

You could also use these as base classes for your own more specific exceptions: this saves a little work because they take care of implementing the what method for you.

Note that deep exception hierarchies can be unusable, because you're basically making a guess in advance about how to categorize the errors, and your clients may disagree.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...