use*_*738 19 c# exception-handling
我想知道可以try..catch
强制执行进入catch
并运行代码吗?
这里的示例代码:
try {
if (AnyConditionTrue) {
// run some code
}
else {
// go catch
}
} catch (Exception) {
// run some code here...
}
Run Code Online (Sandbox Code Playgroud)
cad*_*ll0 28
else
我建议不要在其中抛出异常,而是将代码从您catch
的方法中提取出来并从其他方法中调用
try
{
if (AnyConditionTrue)
{
MethodWhenTrue();
}
else
{
HandleError();
}
}
catch(Exception ex)
{
HandleError();
}
Run Code Online (Sandbox Code Playgroud)
小智 22
try{
if (AnyConditionTrue){
//run some code
}
else{
throw new Exception();
}
}
catch(){
//run some code here...
}
Run Code Online (Sandbox Code Playgroud)
但就像Yuck所说,我不会推荐这个.你应该退后一步,完成你想要完成的任务.有一种更好的方法(即使用正常的条件流,而不是异常处理).
小智 11
是的,你必须抛出异常:
try
{
throw new Exception("hello");
}
catch (Exception)
{
//run some code here...
}
Run Code Online (Sandbox Code Playgroud)
抛出Exception
并跳转到的有效方法Catch
:
try
{
throw new Exception("Exception Message");
}
catch (Exception e)
{
// after the throw, you will land here
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
42658 次 |
最近记录: |