k0d*_*nd0 10 .net c# attributes exception-handling
有没有办法装饰一个会进行一些日志记录的方法,然后无条件地抛出异常,如此?
我有这样的代码:
void foo(out int x)
{
if( condition() ) { x = bar(); return; }
// notice that x is not yet set here, but compiler doesn't complain
throw new Exception( "missed something." );
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试这样写,我会遇到问题:
void foo(out int x)
{
if( condition() ) { x = bar(); return; }
// compiler complains about x not being set yet
MyMethodThatAlwaysThrowsAnException( "missed something." );
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?谢谢.
Mat*_*ted 19
这个怎么样?
bool condition() { return false; }
int bar() { return 999; }
void foo(out int x)
{
if (condition()) { x = bar(); return; }
// compiler complains about x not being set yet
throw MyMethodThatAlwaysThrowsAnException("missed something.");
}
Exception MyMethodThatAlwaysThrowsAnException(string message)
{
//this could also be a throw if you really want
// but if you throw here the stack trace will point here
return new Exception(message);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2540 次 |
| 最近记录: |