关于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;
}
}
在类Test中ReadString1方法会抛出一个异常,怎么样使Main方法在处理string str1 = t.ReadString1();时因为ReadString1方法产生的异常而跳出,也即不再执行string str1 = t.ReadString1();一句之后的语句呢?我想到的一个方法是加一个判断,但那样就相当于对一人东西加了两次判断,不想那样做,请问有什么好的方法么?
[解决办法]
class Program
{
static void Main(string[] args)
{
try
{
Test t = new Test();
string str1 = t.ReadString1();
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 发生的某些异常,有需要手动释放的资源的情况下,将考虑捕获异常,在释放了相关资源后,再将异常抛出,最后由调用方执行相关异常处理。