我正在使用VC#
中的winforms应用程序创建一个类我的问题是如何将一个catched异常返回给类调用者?以此为例:
Public Class test
{
private int i = 0;
public test() { }
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
catch (Exception ex)
{
throw ex;
}
}
}
想象一下在引用这个类的同时在另一个地方调用这个方法。这是一个好主意吗?或者应该怎么做?
答案 0 :(得分:4)
您有几种选择。
根本无法处理异常:
public SetInt()
{
i = "OLAGH"; //This is bad!!!
return i;
}
然后调用者需要处理异常。
如果要处理异常,可以捕获错误并进行处理。
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
catch (FailException ex)
{
return FAIL;
}
}
请注意,捕获基本Exception类是不好的做法。您应该预测可能发生的错误并尝试处理它们。意外的错误和错误的结果,应该发出很大的噪音,以便您可以收到其他问题的警报并修复它们。
如果您想提出自己的异常,可以这样做:
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
catch (FailException ex)
{
throw new SetIntFailException ( ex );
}
}
然后调用者负责处理SetIntFailException,而不是CastFailException或者代码可能抛出的数百种其他异常。
如果您希望调用者处理异常,但您想要进行一些清理,则可以使用finally:
public SetInt()
{
try
{
i = "OLAGH"; //This is bad!!!
return i;
}
finally
{
// Cleanup.
}
}
即使存在异常,也会始终调用finally块中的代码,但错误仍会被提升到调用者。
我假设在您的真实代码中,它至少会编译! ; - )
答案 1 :(得分:1)
首先,代码无法编译。
public class test
{
private int i = 0;
public test(){}
public SetInt(object obj)
{
try
{
i = (int) obj;
return i;
}
catch(exception ex)
{
throw; // This is enough. throwing ex resets the stack trace. This maintains it
}
}
}
如果你想抛出异常,请执行以下操作:
throw new Exception ("My exception");
如果要保留一些特定于异常的详细信息,可以创建一个派生自Exception的类。