21xrx.com
2025-06-30 15:09:16 Monday
文章检索 我的文章 写文章
C++中如何抛出异常并显示异常的行号和文件
2023-07-03 22:42:34 深夜i     73     0
C++ 异常处理 行号 文件

C++是一种广泛使用的计算机编程语言,它在软件开发中被广泛应用。异常处理是C++中一个非常重要的机制,当程序执行过程中遇到错误时,可以通过抛出异常来终止程序的执行并处理错误。

在C++中,可以使用标准库提供的exception类来抛出异常,并显示异常的行号和文件。具体步骤如下:

1. 引入头文件

在程序中引入 头文件,以便使用exception类。

2. 定义异常类

定义一个继承自exception类的异常类,用于抛出异常。可以在该异常类中定义构造函数,以便在抛出异常时传递错误信息。

例如,定义一个异常类MyException:

#include <exception>
class MyException : public std::exception
{
public:
  MyException(const char* message, const char* file, int line)
  
    m_message = message;
    m_file = file;
    m_line = line;
  
  
  virtual const char* what() const throw()
  {
    return m_message.c_str();
  }
  
  const char* file() const throw()
  {
    return m_file.c_str();
  }
  
  int line() const throw()
  
    return m_line;
  
  
private:
  std::string m_message;
  std::string m_file;
  int m_line;
};

该异常类包括了错误信息、文件名和行号等信息,并重载了what()方法来返回错误信息。

3. 抛出异常

在程序中使用throw语句抛出异常。可以使用MyException类的构造函数传递错误信息,并使用__FILE__和__LINE__宏分别获取文件名和行号。

例如:

#include <iostream>
#include <exception>
#include "MyException.h"
void testFunc()
{
  throw MyException("error occurred", __FILE__, __LINE__);
}
int main()
{
  try
  {
    testFunc();
  }
  catch(const MyException& e)
  {
    std::cout << "Exception occurred in " << e.file() << " at line " << e.line() << ": " << e.what() << std::endl;
  }
  
  return 0;
}

程序中的testFunc函数抛出了一个MyException类型的异常,传递了错误信息和文件名、行号等信息。在main函数中使用try-catch语句捕获异常,并调用MyException类中的file()和line()方法输出文件名和行号信息。输出结果为:

Exception occurred in main.cpp at line 9: error occurred

因此,可以使用C++中的exception类来抛出并捕获异常,并显示异常的行号和文件。这对于调试程序和处理错误非常有用。

  
  

评论区