C 學習 C 異常

2021-10-21 12:09:47 字數 2072 閱讀 7830

異常處理就是處理程式中的錯誤。所謂錯誤是指在程式執行的過程中發生一些異常事件(如:除0溢位,陣列下標越界,所要讀取的檔案不存在,空指標,記憶體不足等等)

try 試圖執行{}中的內容,在可能出現異常的地方,丟擲異常throw,try下面catch捕獲異常。如果不想處理異常,繼續向上丟擲 throw,如果沒有任何處理異常的地方,那麼成員呼叫terminate函式,程式中斷

int mydevice(int a, int b)

return a / b;

}void test01()

catch (int) //捕獲異常

catch(...)

}

//自定義異常類

class myexception

};int mydevice(int a, int b)

return a / b;

}void test01()

catch (myexception e)

}

從try開始  到throw 丟擲異常之前 所有棧上的物件 都會釋放 這個過程稱為棧解旋

構造和析構順序是相反的

//自定義異常類

class myexception

};class person

~person() };

int mydevide(int a, int b)

return a / b;

}void test01()

catch (myexception e)

}

只想丟擲乙個特定型別的異常,其他的都不丟擲

只能在qt或linux下應用

void func() throw(int)  //throw(int)只能丟擲int型別異常,throw()不丟擲任何型別異常

void test01()

catch(int)

}

myexception e因為呼叫拷貝構造,會多開銷乙份資料

myexception *e,不new的話會提前釋放物件  new自己管理delete

myexception &e,容易些,而且 就乙份資料

class myexception

~myexception()

myexception(const myexception &e) };

void dowork()

void test01()

catch (myexception &e) //myexception e因為呼叫拷貝構造,會多開銷乙份資料

}

利用多型來實現 printerror同乙個介面呼叫,丟擲不同的錯誤物件,提示不同的錯誤

class baseexception

};class nullpointerexception :public baseexception

};class outofrangeexception :public baseexception

};void dowork()

void test01()

catch (baseexception &e)

}

//系統提供標準異常,要包含標頭檔案

#include

class person

} string m_name;

int m_age;

};void test02()

catch (out_of_range &e)

catch (length_error &e)

}

//編寫自己的異常類, 繼承系統標準異常類

class myoutofrangeexception :public exception

virtual ~myoutofrangeexception()

virtual char const* what() const

string m_errorinfo;

};

c 入門學習 異常

1.異常 1.1 異常的丟擲 異常丟擲使用throw關鍵字,使用語法為 throw 異常 異常是個物件,如int i 1 throw i等。也可以自定義乙個異常類,在必要的時候丟擲該異常類的例項 class myexception throw myexception 這裡不能使用throw myex...

C 異常學習筆記

vc 中的異常捕獲的規則 可以捕獲的異常有以下三種情況 1.必須嚴格遵守匹配資料型別 2.異常處理的資料型別是公有類,拋擲的異常的資料型別是派生類。3.異常處理的資料型別是指向公有基類的指標,拋擲異常的資料型別是指向派生類的執針 對於派生層次結構的異常處理,catch 塊組的順序是重要的。因為 ca...

c 異常學習筆記

1.捕獲異常 try catch結構 2.收尾工作 try catch finally結構 3.丟擲異常 throw語句 try catch finally結構 class program denominator,result catch dividebyzeroexception e 分母為0的異...