qfedu-cpp-level/day8/homework/h4.cpp

55 lines
1.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个C++ 程序,动态分配一个整型数组,并根据用户输入的索引值访问数组元素。 在访问数组元素时处理以下异常情况: 1如果数组分配内存失败则抛出一个自定义的异常对象 MemoryAllocationException。 2如果用户输入的索引超出了数组的范围则抛出一个自定义的异常对象 IndexOutOfBoundsException。
// 【要求】在 main 函数中调用动态内存分配函数,并捕获并处理可能抛出的异常。
#include <bits/stdc++.h>
using namespace std;
// 自定义异常类
class MemoryAllocationException : public exception
{
public:
const char *what() const throw()
{
return "内存分配异常";
}
};
class IndexOutOfBoundsException : public exception
{
public:
const char *what() const throw()
{
return "索引越界异常";
}
};
int main()
{
int *arr = new int[10]; // 动态分配一个整型数组
try
{
if (arr == NULL)
throw MemoryAllocationException();
// 当不抛出异常时,继续执行数组的赋值操作
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4; // 其余元素会被初始化为 0
int n;
cout << "请输入索引值: ";
cin >> n;
if (n < 0 || n > 9)
throw IndexOutOfBoundsException();
// 当不抛出异常时,继续执行数组的访问操作
cout << "arr[" << n << "] = " << arr[n] << endl;
}
catch (exception &e)
{
cout << "捕获异常: " << e.what() << endl;
}
return 0;
}