C++中try/catch/throw的使用
C++異常是指在程序運行時發生的反常行為,這些行為超出了函數正常功能的范圍。當程序的某部分檢測到一個它無法處理的問題時,需要用到異常處理。異常提供了一種轉移程序控制權的方式。C++異常處理涉及到三個關鍵字:try、catch、throw。
在C++語言中,異常處理包括:
(1)、throw表達式:異常檢測部分使用throw表達式來表示它遇到了無法處理的問題,throw引發了異常。throw表達式包含關鍵字throw和緊隨其后的一個表達式,其中表達式的類型就是拋出的異常類型。throw表達式后面通常緊跟一個分號,從而構成一條表達式語句。
(2)、try語句塊:異常處理部分使用try語句塊處理異常。try語句塊以關鍵字try開始,并以一個或多個catch子句結束。try語句塊中代碼拋出的異常通常會被某個catch子句處理。因為catch子句處理異常,所以它們也被稱作異常處理代碼。catch子句包括三部分:關鍵字catch、括號內一個(可能未命名的)對象的聲明(稱作異常聲明,exception ?declaration)以及一個塊。當選中了某個catch子句處理異常之后,執行與之對應的塊。catch一旦完成,程序跳轉到try語句塊最后一個catch子句之后的那條語句繼續執行。try語句塊聲明的變量在塊外部無法訪問,特別是在catch子句內也無法訪問。如果一段程序沒有try語句塊且發生了異常,系統會調用terminate函數并終止當前程序的執行。
(3)、一套異常類(exception class):用于在throw表達式和相關的catch子句之間傳遞異常的具體信息。
C++標準庫定義了一組類,用于報告標準庫函數遇到的問題。這些異常類也可以在用戶編寫的程序中使用,它們分別定義在4個頭文件中:
(1)、exception頭文件定義了最通常的異常類exception,它只報告異常的發生,不提供任何額外的信息。
(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的測試代碼,詳細內容介紹可以參考對應的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
總結
以上是生活随笔為你收集整理的C++中try/catch/throw的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Caffe源码中Solver文件分析
- 下一篇: Caffe中对MNIST执行train操