簡體   English   中英

C++ - 構造函數中的異常

[英]C++ - Exception in Constructor

我有個問題。 我必須在構造函數 One() 中拋出一個異常,但不知道我該如何捕捉它。 有人可以建議嗎? 我試過這個方法: 從構造函數拋出異常如果構造函數拋出異常會發生什么?

我的代碼:

class One
{
    int a, b;

public:

    One()
    {
        a = 7;
        b = 0;
        if (b == 0)
        {
            throw "except";
        }       
    }

};
int main()
{
    One j;
    try 
    {
        cout << "good"; 
    }
    catch(const char *str)
    {
        cout << str;
    }
}

將變量定義放在try塊中:

try 
{
    One j;
    std::cout << "good"; 
}
catch(const char *str)
{
    std::cout << str;
}

首先,不要拋出非異常。 2. 如果在 try 塊內調用構造函數,則可以捕獲它。

#include <iostream>
#include <stdexcept>

class One
{
    int a, b;
public:
    One():
     a(7),
     b(0) 
   {
        if (b == 0) {
            throw std::runtime_error("except");
        }       
   }

};

...

try { 
   One j; 
   std::cout << "good" << std::endl; 
} catch(std::exception& e) { 
   std::cerr << e.what() << std::endl; 
} 

如果您不想將整個代碼放在 try..catch 塊中,則另一種解決方案:

int main()
{
  One* j = nullptr;
  try 
  {
      j = new One;
      cout << "good"; 
  } catch (const char *str)
  {
      cout << str;
      return 0;
  }
  // continue with object in j ...
}

當然,在這種情況下,您應該使用智能指針:

int main()
{
  std::unique_ptr< One> j;
  try 
  {
      j.reset( new One());   // or use std::make_unique<>()
      cout << "good"; 
  } catch (const char *str)
  {
      cout << str;
      return 0;
  }
  // continue with object in j ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM