关于C#中的try ,catch问题

来源:百度知道 编辑:UC知道 时间:2024/05/09 13:27:43
try
{
smallfoldername = Server.MapPath(ConfigurationManager.AppSettings["SmallPath"]);
bigfoldername = Server.MapPath(ConfigurationManager.AppSettings["NormalPath"]);
}
catch
{
smallfoldername = Server.MapPath("./Photo/SmallPics/");
bigfoldername = Server.MapPath("./Photo/NormalPics/");
}
这是程序中的一段代码,程序能正常运行,请部catch不是找错吗,怎么这里面catch在搞什么啊?

在C#中catch后是可以不写像(Exception e)这种的,上面代码的意思就是,当try块出问题后,执行catch块中的代码。

这么写根本就不是try catch的正常用法.仅仅目前的功能完全可以去掉
可以用
smallfoldername = Server.MapPath(ConfigurationManager.AppSettings["SmallPath"]);
if(String.IsNullOrEmpty(smallfoldername))
smallfoldername = Server.MapPath("./Photo/SmallPics/");

bigfoldername = Server.MapPath(ConfigurationManager.AppSettings["NormalPath"]);
if(String.IsNullOrEmpty(bigfoldername))
bigfoldername = Server.MapPath("./Photo/NormalPics/");

在try...catch块中,设定了两个变量,变量需要读取配置文件中两个键的值,当读取发生错误的时候就在catch中将两个变量设默认值。
这样是可以的,有时候在catch中出了要把错误写出来之外,也要写一些以防程序崩溃的代码,就像这个代码,如果不赋这两个值也许在程序后方会让程序崩溃。

catch(Exception e)
{
messagebox.show(e.messges);

}

后面该这样吧

catch (例外类型 变量)

没捕捉到错或已处理了,在catch 中加入messagebox.show(ex.message)看看写的啥吧