日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 人文社科 > 生活经验 >内容正文

生活经验

C++中try/catch/throw的使用

發(fā)布時(shí)間:2023/11/27 生活经验 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++中try/catch/throw的使用 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

C++異常是指在程序運(yùn)行時(shí)發(fā)生的反常行為,這些行為超出了函數(shù)正常功能的范圍。當(dāng)程序的某部分檢測(cè)到一個(gè)它無(wú)法處理的問(wèn)題時(shí),需要用到異常處理。異常提供了一種轉(zhuǎn)移程序控制權(quán)的方式。C++異常處理涉及到三個(gè)關(guān)鍵字:try、catch、throw。

在C++語(yǔ)言中,異常處理包括:

(1)、throw表達(dá)式:異常檢測(cè)部分使用throw表達(dá)式來(lái)表示它遇到了無(wú)法處理的問(wèn)題,throw引發(fā)了異常。throw表達(dá)式包含關(guān)鍵字throw和緊隨其后的一個(gè)表達(dá)式,其中表達(dá)式的類型就是拋出的異常類型。throw表達(dá)式后面通常緊跟一個(gè)分號(hào),從而構(gòu)成一條表達(dá)式語(yǔ)句。

(2)、try語(yǔ)句塊:異常處理部分使用try語(yǔ)句塊處理異常。try語(yǔ)句塊以關(guān)鍵字try開始,并以一個(gè)或多個(gè)catch子句結(jié)束。try語(yǔ)句塊中代碼拋出的異常通常會(huì)被某個(gè)catch子句處理。因?yàn)閏atch子句處理異常,所以它們也被稱作異常處理代碼。catch子句包括三部分:關(guān)鍵字catch、括號(hào)內(nèi)一個(gè)(可能未命名的)對(duì)象的聲明(稱作異常聲明,exception ?declaration)以及一個(gè)塊。當(dāng)選中了某個(gè)catch子句處理異常之后,執(zhí)行與之對(duì)應(yīng)的塊。catch一旦完成,程序跳轉(zhuǎn)到try語(yǔ)句塊最后一個(gè)catch子句之后的那條語(yǔ)句繼續(xù)執(zhí)行。try語(yǔ)句塊聲明的變量在塊外部無(wú)法訪問(wèn),特別是在catch子句內(nèi)也無(wú)法訪問(wèn)。如果一段程序沒(méi)有try語(yǔ)句塊且發(fā)生了異常,系統(tǒng)會(huì)調(diào)用terminate函數(shù)并終止當(dāng)前程序的執(zhí)行。

(3)、一套異常類(exception class):用于在throw表達(dá)式和相關(guān)的catch子句之間傳遞異常的具體信息。

C++標(biāo)準(zhǔn)庫(kù)定義了一組類,用于報(bào)告標(biāo)準(zhǔn)庫(kù)函數(shù)遇到的問(wèn)題。這些異常類也可以在用戶編寫的程序中使用,它們分別定義在4個(gè)頭文件中:

(1)、exception頭文件定義了最通常的異常類exception,它只報(bào)告異常的發(fā)生,不提供任何額外的信息。

(2)、stdexcept頭文件定義了幾種常用的異常類,如下(《C++ Primer(Fifth Edition)》):

(3)、new頭文件定義了bad_alloc異常類型。

(4)、type_info頭文件定義了bad_cast異常類型。

Exceptions provide a way to react to exceptional circumstances (like run time errors) in programs by transferring control to special functions called handlers.

To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing that portion of code in a try-block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block.

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.

C++provides a list of standard exceptions defined in <exception> ( https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm?):

下面是從其他文章中copy的測(cè)試代碼,詳細(xì)內(nèi)容介紹可以參考對(duì)應(yīng)的reference:

#include "try_catch.hpp"
#include <iostream>
#include <exception>
#include <vector>//
// reference: http://www.cplusplus.com/doc/tutorial/exceptions/
int test_exception1()
{try {throw 20;}catch (int e) {std::cout << "An exception occurred. Exception Nr. " << e << '\n';}return 0;
}class myexception : public std::exception
{virtual const char* what() const throw(){return "My exception happened";}
} myex;int test_exception2()
{try {throw myex;}catch (std::exception& e) { // catches exception objects by reference (notice the ampersand & after the type)std::cout << e.what() << '\n';}return 0;
}int test_exception3()
{
/*exception		descriptionbad_alloc		thrown by new on allocation failurebad_cast		thrown by dynamic_cast when it fails in a dynamic castbad_exception		thrown by certain dynamic exception specifiersbad_typeid		thrown by typeidbad_function_call	thrown by empty function objectsbad_weak_ptr		thrown by shared_ptr when passed a bad weak_ptr
*/try {int* myarray = new int[1000];}catch (std::exception& e) { // Takes a reference to an 'exception' objectstd::cout << "Standard exception: " << e.what() << std::endl;}return 0;
}///
// reference: http://en.cppreference.com/w/cpp/language/try_catch
int test_exception4()
{try {std::cout << "Throwing an integer exception...\n";throw 42;}catch (int i) {std::cout << " the integer exception was caught, with value: " << i << '\n';}try {std::cout << "Creating a vector of size 5... \n";std::vector<int> v(5);std::cout << "Accessing the 11th element of the vector...\n";std::cout << v.at(10); // vector::at() throws std::out_of_range}catch (const std::exception& e) { // caught by reference to basestd::cout << " a standard exception was caught, with message '"<< e.what() << "'\n";}return 0;
}/
// reference: https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
static int division(int a, int b) {if (b == 0) {throw "Division by zero condition!";}return (a / b);
}int test_exception5()
{int x{ 50 }, y{ 0 }, z{ 0 };try {z = division(x, y);std::cout << z << std::endl;}catch (const char* msg) {std::cerr << msg << std::endl;}return 0;
}struct MyException : public std::exception
{const char * what() const throw () {return "C++ Exception";}
};int test_exception6()
{try {throw MyException();}catch (MyException& e) {std::cout << "MyException caught" << std::endl;std::cout << e.what() << std::endl;}catch (std::exception& e) {//Other errors}return 0;
}int test_exception7()
{try {char* str = nullptr;str = new char[10];if (str == nullptr) throw "Allocation failure";for (int n = 0; n <= 100; n++) {if (n > 9) throw n;str[n] = 'z';}}catch (int i) {std::cout << "Exception: ";std::cout << "index " << i << " is out of range" << std::endl;}catch (char * str) {std::cout << "Exception: " << str << std::endl;}return 0;
}

GitHub:https://github.com/fengbingchun/Messy_Test

總結(jié)

以上是生活随笔為你收集整理的C++中try/catch/throw的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。