提交 666dad25 编写于 作者: W wsb

自定义异常

上级 adee04a8
......@@ -3,4 +3,4 @@ project(cpp_15_exception)
set(CMAKE_CXX_STANDARD 11)
add_executable(cpp_15_exception main.cpp)
add_executable(cpp_15_exception main.cpp MyException.cpp MyException.h)
//
// Created by 11010 on 2023/4/9.
//
#include "MyException.h"
const char *MyException::what() const throw() {
return "CPP error,Çë¼ì²â³ÌÐò£¡";
}
//
// Created by 11010 on 2023/4/9.
//
#ifndef CPP_15_EXCEPTION_MYEXCEPTION_H
#define CPP_15_EXCEPTION_MYEXCEPTION_H
#include "exception"
class MyException :public std::exception{
public:
const char * what() const throw() override; //重写what函数:用于返回当前程序的具体异常描述
};
#endif //CPP_15_EXCEPTION_MYEXCEPTION_H
#include <iostream>
#include "MyException.h"
#include "exception"
int result(int a, int b);
......@@ -28,7 +30,22 @@ int main() {
}
//通过继承和重载 exception 类来定义新的异常
//通过继承和重载 exception 类来定义新的异常: 定义新的类MyException继承exception自定义新的异常
try {
throw MyException(); //抛出自定义异常
}
//捕获异常
catch (MyException& e){
std::cout<<e.what()<<std::endl;
}
//使用c++标准异常
try {
throw std::bad_exception();
}catch (std::bad_exception& e){
std::cout<< e.what()<<std::endl;
}
return 0;
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册