c#如何在函数返回时同时抛出异常

aqjy 2008-12-14 08:01:06
例有如下函数:
public int DeleteFile(string fileName)
{
try
{
File.Delete(fileName);
return 0;
}
catch (Exception ee)
{
throw ee;
return 1;
}
}
编译提示 return 1无效(若先 return 1; 再 throw ee,编译提示 throw ee无效)而我希望在发生异常时,既能返回数值1,又能在调用该函数的父函数中处理异常,该怎么做?
...全文
569 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
cyqlightrain 2008-12-14
  • 打赏
  • 举报
回复
public int DeleteFile(string fileName,out Exception ex)
{
Exception ex = null;
try
{
File.Delete(fileName);
return 0;
}
catch (Exception ee)
{
throw ee;
//return 1;
}
return 1;
}


试试这个!
烈火蜓蜻 2008-12-14
  • 打赏
  • 举报
回复
try
{
......
}
catch(Exception的子类)
{}
catch(Exception的子类)
{}
catch(Exception的子类)
{}
catch(Exception的子类)
{}
catch(Exception的子类)
{}
catch(Exception的子类)
{}
catch(Exception)
{}

多少不同的类都可以处理
qqlpp 2008-12-14
  • 打赏
  • 举报
回复
不懂,up
SpaceTime 2008-12-14
  • 打赏
  • 举报
回复
如果想用系统自己的异常信息
public int DeleteFile(string fileName)
{
try
{
File.Delete(fileName);
return 0;
}
catch (Exception ee)
{
throw new Exception(ee.Message + "1");
}
}
SpaceTime 2008-12-14
  • 打赏
  • 举报
回复
public int DeleteFile(string fileName)
{
try
{
File.Delete(fileName);
return 0;
}
catch ()
{
throw new Exception("异常信息。" + "1");
}
}
解析一下Ex.Message就可以了
aqjy 2008-12-14
  • 打赏
  • 举报
回复
如果要实现这样的功能可以怎样变通?
如果通过在调用的父函数中处理返回的值,就无法处理不同的异常信息,若通过异常处理返回值,又不容易在父函数中处理其它语句。
烈火蜓蜻 2008-12-14
  • 打赏
  • 举报
回复
不要试了,这是不合理的,也是完全没有意义的
flyjimi 2008-12-14
  • 打赏
  • 举报
回复
1楼,2楼,这样的编译都过不去。
楼主是想要在出现异常的时候,抛出异常同时return一个值?这个想法不现实。return 和你的throw是不会同时执行到的。
应该是 要么抛异常,要么返回值。只能是“或”。
aqjy 2008-12-14
  • 打赏
  • 举报
回复
public int DeleteFile(string fileName)
{
int i;
try
{
File.Delete(fileName);
i=0;
}
catch (Exception ee)
{
i=1;
throw ee;

}
finally{
return i;
}
}
编译后有错误,“控制不能离开finally主体"
pinyu 2008-12-14
  • 打赏
  • 举报
回复
public int DeleteFile(string fileName)
{
try
{
File.Delete(fileName);
return 0;
}
catch (Exception ee)
{
throw ee;
}
finally

return 1;

}
lvfeng19806001 2008-12-14
  • 打赏
  • 举报
回复
public int DeleteFile(string fileName)
{
int i;
try
{
File.Delete(fileName);
i=0;
}
catch (Exception ee)
{
i=1;
throw ee;

}
finally{
return i;
}
}



还是我,这样应该可以

111,093

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧