
异常是C++的一个非常核心的概念。在执行过程中发生不希望或不可能的操作时会发生异常。在C++中处理这些不希望或不可能的操作被称为异常处理。异常处理主要使用三个特定的关键字,它们是‘try’、‘catch’和‘throw’。‘try’关键字用于执行可能遇到异常的代码,‘catch’关键字用于处理这些异常,‘throws’关键字用于创建异常。C++中的异常可以分为两种类型,即STL异常和用户定义的异常。在本文中,我们重点介绍如何创建这些自定义的异常。有关异常处理的更多详细信息可以在此处找到。
首先,我们看到如何使用一个单一的类来创建自定义异常。为此,我们必须定义一个类并抛出该类的异常。
//user-defined class
class Test{};
try{
//throw object of that class
throw Test();
}
catch(Test t) {
....
}
#include <iostream>
using namespace std;
//define a class
class Test{};
int main() {
try{
//throw object of that class
throw Test();
}
catch(Test t) {
cout << "Caught exception 'Test'!" << endl;
}
return 0;
}
Caught exception 'Test'!
‘try’块会抛出该类的异常,而‘catch’块只会捕获该特定类的异常。如果有两个用户定义的异常类,那么必须分别处理它们。
这个过程很简单,如预期的那样,如果有多个异常情况,每个都必须单独处理。
立即学习“C++免费学习笔记(深入)”;
//user-defined class
class Test1{};
class Test2{};
try{
//throw object of the first class
throw Test1();
}
catch(Test1 t){
....
}
try{
//throw object of the second class
throw Test2();
}
catch(Test2 t){
....
}
#include <iostream>
using namespace std;
//define multiple classes
class Test1{};
class Test2{};
int main() {
try{
//throw objects of multiple classes
throw Test1();
}
catch(Test1 t) {
cout << "Caught exception 'Test1'!" << endl;
}
try{
throw Test2();
}
catch(Test2 t) {
cout << "Caught exception 'Test2'!" << endl;
}
return 0;
}
Caught exception 'Test1'! Caught exception 'Test2'!
我们不得不使用两个不同的try-catch块来处理两种不同类别的异常。现在我们看看是否可以使用构造函数创建和处理异常。
我们可以使用类构造函数来创建自定义异常。在下面的示例中,我们可以看到异常的抛出和处理都在类构造函数内部进行管理。
#include <iostream>
using namespace std;
//define a class
class Test1{
string str;
public:
//try-catch in the constructor
Test1(string str){
try{
if (str == "Hello"){
throw "Exception! String cannot be 'Hello'!";
}
this->str = str;
}
catch(const char* s) {
cout << s << endl;
}
}
};
int main() {
Test1 t("Hello");
return 0;
}
Exception! String cannot be 'Hello'!
异常处理是C++提供的最重要的功能之一。我们可以继承C++异常类并使用它来实现异常处理,但这只是良好的实践,不是创建自定义异常所必需的。继承C++异常类的好处是,如果有一个普通的catch语句捕获std::exception,它可以处理任何用户定义的异常而不需要知道具体细节。需要注意的是,'throws'语句只在'try'块内起作用,否则不起作用。'catch'语句只能处理由用户定义的类或某些STL类抛出的异常。
以上就是C++程序创建自定义异常的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号