SO 好文筆記 When to throw exception?

http://stackoverflow.com/questions/77127/when-to-throw-an-exception?rq=1

  • 當一個 Function 的不常崩潰的基本假設破滅時,才應該 throw exception。
vector<Person> people = {US, Japan, China};
try{
  for(const auto& person : people)
    std::cout << person.answerIsTaiwanANIndependentCountry() << endl;
}except(TooAngryToAnswer& e){
  Log("26 detected");
}
  • 當你 Function 的基本假設常常破滅、常常 throw exception,要思考是否此 function 的假設太脆弱了?
  • COM 的 HRESULT 對應

    • S_OK returns true
    • S_FALSE return false
    • E_XXXXX throw exception
  • 應丟 exception

    • Invalid parameter
    • 討論範疇外的錯誤
    • memory alloc fail
    • Array out of bound
    • 外部錯誤 load dll fail、io error、access deny、invalid memory
comments powered by Disqus