1. 程式人生 > >NDK 異常處理 學習

NDK 異常處理 學習

1.在C++ 層如果是自己寫的程式碼 或者呼叫別人的方法,記得要 catch 異常,如果不try catch ,在java層是 try catch 不住的,肯定會掛掉
    
    2.如果異常需要往外拋 給java 層 ,一定要按照java 層拋異常的方式  
    

try{
    }catch(const Exception& e){
        env->FindClass("java/lang/Exception");
        env->ThrowNew(je,e.what());
    }


    3.如果是自己寫的NDK 程式碼,最好拋自己寫的異常 ,宣告異常 
    
    4.如果是做 C / C++ , 最好拋系統定義好的異常,或者繼承系統的異常 
    
    5. 系統異常的體系 Exception 基類  (  #include <stdexcept>)

對std::out_of_range丟擲異常進行處理 ,標頭檔案stdexcept

#include <iostream>  
#include <vector>  
#include <stdexcept>  
using namespace std;  
int main() {  
    vector <int> a;  
    a.push_back(1);  
    try {  
        a.at(1);  
    }  
    catch (std::out_of_range &exc) {  
        std::cerr << exc.what() << " Line:" << __LINE__ << " File:" << __FILE__ << endl;  
    }  
    return EXIT_SUCCESS;  
}   

 這樣就能知道在第幾行和哪個檔案中了。

說明編輯

C++異常類,繼承自logic_error,logic_error的父類是exception。屬於執行時錯誤,如果使用了一個超出有效範圍的值,就會丟擲此異常。也就是一般常說的越界訪問。定義在名稱空間std中。

使用時須包含標頭檔案 #include<stdexcept>

out_of_range例子

編輯

// out_of_range example

#include<iostream>

#include<stdexcept>

#include<vector>

using namespace std;//或者用其他方式包含using std::logic_error;和using std::out_of_range;

int main (void)

{

vector<int> myvector(10);

try

{

myvector.at(20)=100; // vector::at throws an out-of-range

}

catch (out_of_range& oor)

{

cerr << "Out of Range error: " << oor.what() << endl;

}

getchar();

return 0;

}

myvector只有10個元素,所以myvector.at(20)就會丟擲out_of_range異常。