关于Try_Catch的一个问题
在复习Try_Catch的时候遇到了一个问题,先看代码:
class Program
{
static void Main(string[] args)
{
Test t = new Test();
string str1 = t.ReadString1();
Console.WriteLine(str1);
string str2 = t.ReadString2();
Console.WriteLine(str2);
Console.ReadLine();
}
}
class Test
{
public string ReadString2()
{
Console.WriteLine("我是DoWork");
return "DoW";
}
public string ReadString1()
{
string str1 = string.Empty;
try
{
if (string.IsNullOrWhiteSpace(str1))
{
throw new Exception("The value is null!");
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
return str1;
}
}
Console.WriteLine(str1);
string str2 = t.ReadString2();
Console.WriteLine(str2);
Console.ReadLine();
}
catch { }
}
}
class Test
{
public string ReadString2()
{
Console.WriteLine("我是DoWork");
return "DoW";
}
public string ReadString1()
{
string str1 = string.Empty;
try
{
if (string.IsNullOrWhiteSpace(str1))
{
throw new Exception("The value is null!");
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
throw new Exception(e.Message);
}
return str1;
}
}
[解决办法]
在Main方法里用try...catch,取消Text.ReadString1里的try...catch,这样有异常的话就可以在Main里的catch处理了。同3楼
[解决办法]
如果 Test.ReadString1 的约定是发生异常后将终止后继操作,那么此方法内部就不需要捕获异常了,应该由调用方来捕获异常。
如果 Text.ReadString1 发生的某些异常,有需要手动释放的资源的情况下,将考虑捕获异常,在释放了相关资源后,再将异常抛出,最后由调用方执行相关异常处理。