using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Photo
{//Photo类
string _title;
public Photo(string title)
{//构造函数
this._title = title;
}
public string Title
{//访问器
get
{
return _title;
}
}
public override string ToString()
{
try
{
return _title;
}
catch (NullReferenceException e)
{
throw new NullReferenceException("Not Found");
}
}
}
class Album
{
// 该数组用于存放照片
Photo[] photos;
public Album(int capacity)
{
photos = new Photo[capacity];
}
public Photo this[int index]
{//索引器
set {
if (index<0 || index>=photos.Length)
Console.WriteLine("Wrong Index");
else
photos[index] = value; }
get {
if (index < 0 || index >= photos.Length)
return null;
return photos[index]; }
}
public Photo this[string str]
{//索引器
get {
int i = 0;
while (i < photos.Length)
{
if (photos[i].ToString() == str)
return photos[i];
i++;
};
return null;
}
}
}
class Program
{
static void Main(string[] args)
{
// 创建一个容量为 3 的相册
Album family = new Album(3);
// 创建 3 张照片
Photo first = new Photo("Jeny ");
Photo second = new Photo("Smith");
Photo third = new Photo("Lono");
// 向相册加载照片
family[0] = first;
family[1] = second;
family[2] = third;
// 按索引检索
Photo objPhoto1 = family[2];
Console.WriteLine(objPhoto1.Title);
// 按名称检索
Photo objPhoto2 = family["Jeny"];
Console.WriteLine(objPhoto2.Title);
Console.Read();
}
}
}
运行后报错,原因在于Photo objPhoto2 = family["Jeny"]中"Jeny"与"Jeny "(Jeny后有空格)不相等,索引器返回值为null。此时objPhoto2为null,不能执行Console.WriteLine(objPhoto2.Title);
请问这个异常是谁呢么类型的异常?我该如何使用异常处理,使其输出“Not Found”?
如果不是在自己重写的Tostring()函数中,那么应当在那里捕获这个异常?
第一次提问,略惶恐,先谢谢前辈们
在toString中没有必要使用try...catch
完全可以if判断下objPhoto2是否null
我感觉try...catch没有必要刻意去使用,简单的用if就行,真的是有必要的时候用才是最合理的
真想用的话
try
{
Console.WriteLine(objPhoto2.Title);;
}
catch (NullReferenceException e)
{
throw new NullReferenceException("Not Found");
}
规范的做法是在索引器内throw InvalidArgumentException();