基本上有两组可能的解决方案:使用异常和不使用。
使用例外,我建议让它冒泡,正如我在 cmets 中已经说过的那样。
然后你可以重新抛出:
try {
// exception here
}
catch(Exception ex)
{
throw;
// Attention: this is _different_ from "throw ex" !!
}
注意这里:
您还可以在 catch 块中使用 throw e 语法来实例化您传递给调用者的新异常。 在这种情况下,原始异常的堆栈跟踪(可从 StackTrace 属性获得)不会保留。
见throw (C# Reference)(我强调)
我自己是从 Java 过来的,这是像我这样的人在从 Java 过渡到 .Net 时会遇到的问题。因此,如果您的团队中有新的“java 人”:不要对他们苛刻,只需将他们指向文档即可。
你可以换行:
try {
// exception here
}
catch(Exception inner)
{
throw new MyCustomException( "Some custom message", inner);
}
顺便说一句:捕获异常通常不是一个好主意。大多数时候,您希望捕获您可以实际处理的特定异常。
另一类解决方案是没有冒泡异常:
返回值:
public static bool Subfunction()
{
bool success = true;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = false;
}
return success;
}
或者带有返回码或错误码:
// DO NOT USE MAGIC NUMBERS !
private static readonly int SUCCESS_INDICATOR = 0;
private static readonly int ERROR_INDICATOR = 1;
// TODO DOCUMENT which errorcodes can be expected and what they mean!
public static int Subfunction()
{
int success = SUCCESS_INDICATOR;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = ERROR_INDICATOR;
}
return success;
}
尤其是团队中有“C-Guys”时,您可能会偶然发现这个。 (无意冒犯 - 只是我的经验)
或者使用状态对象...
public static void Mainfunction()
{
try
{
//some code
//some code
ISuccessIndicator success = new ISIImplementation();
Subfunction( success );
if( !succes.HasException )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThrirdFunction or "else" branch are caught here.
}
}
public static void Subfunction( ISuccessIndicator result )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
result.HasException=true;
result.Exception = ex;
}
}
public interface ISuccessIndicator
{
Exception Exception {get; set;}
bool HasException {get; set;}
}
如果你真的疯了,你可以......
public static void Mainfunction()
{
try
{
//some code
//some code
Exception ex = null;
Subfunction( ref ex );
if( ex == null ) // or more modern: ( ex is null )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThirdFunction or "else" branch caught here.
}
}
public static void Subfunction( ref Exception outEx )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
outEx = ex;
}
}
请注意,我绝不会鼓励使用后者。但这是可能的 ...并且 OP 要求提供可能性。
免责声明:所有 sn-ps 未经测试。谁发现错误可以保留它们(但请写评论,以便我修复它们)。