前向声明可能引起的new崩溃

试试:

a.h

#pragma once

struct RandomData;

class A
{
public:
	A();
	~A();

	bool Run();
private:
	RandomData *m_pData;
};

a.cpp

#include <iostream>
#include "a.h"

struct RandomData
{
	int n;
};

A::A()
	:m_pData(NULL)
{
}

A::~A()
{
}

bool A::Run()
{
	if(NULL == m_pData)
	{
		m_pData = new (std::nothrow) RandomData;
		if(NULL == m_pData)
		{
			return false;
		}
		m_pData->n = 2;
	}
}


main.cpp

#include <iostream>

#include "a.h"

using namespace std;

int main(int argc, char *argv[])
{
	A a;
	a.Run();
	return 0;
}

Makefile

test:main.cpp a.cpp
	g++ -o $@ $^
clean:
	-rm test



你的理解很不错,Java中的异常处理机制是一种能够在程序运行时检测到错误并进行相应处理的机制。在Java中,所有的异常都是Throwable类或其子类的实例。Throwable类有两个直接的子类:Error和Exception。Error代表JVM运行时出现的错误,无法恢复,例如OutOfMemoryError;而Exception分为两种:一种是RuntimeException及其子类,这些异常通常表示程序运行时出现了逻辑错误或者代码缺陷,例如NullPointerException、ArrayIndexOutOfBoundsException等;另一种是非RuntimeException及其子类,这些异常通常表示程序运行时出现了外部因素引起的问题,例如ClassNotFoundException、FileNotFoundException等。 在Java中,我们可以使用try-catch-finally语句块来捕获和处理异常。try块中的语句被执行,如果其中出现了异常,则会跳转到catch块中执行相应的代码。finally块中的代码无论是否出现异常都会被执行。例如: ```java public class Main { public static void main(String[] args) { String str = null; try { System.out.println(str.length()); } catch (NullPointerException e) { System.out.println("发生了空指针异常:" + e.getMessage()); } finally { System.out.println("无论如何,这里的代码都会被执行。"); } } } ``` 上面的代码中,我们故意将一个字符串变量赋值为null,然后试图调用它的`length()`方法,这样就会触发NullPointerException异常。在catch块中,我们输出异常信息,并在finally块中输出一条语句。无论是否出现异常,finally块中的语句都会被执行。 除了try-catch-finally语句块外,我们还可以使用throws关键字来声明方法可能会抛出哪些异常,这样可以让调用该方法的代码知道需要处理哪些异常。例如: ```java public class Main { public static void main(String[] args) { try { readFile("test.txt"); } catch (FileNotFoundException e) { System.out.println("发生了文件找不到异常:" + e.getMessage()); } } public static void readFile(String fileName) throws FileNotFoundException { File file = new File(fileName); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } scanner.close(); } } ``` 上面的代码中,我们定义了一个readFile方法用于读取指定文件的内容,由于该方法使用了Scanner和File类,这两个类可能会抛出FileNotFoundException异常,因此我们在方法声明中使用throws关键字将该异常抛出,以便调用该方法的代码能够处理该异常。在主方法中,我们调用了readFile方法并捕获了FileNotFoundException异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值