从Python到C#的异常处理让我烦恼的一件事是,在C#中似乎没有任何指定else子句的方法.例如,在Python中我可以写这样的东西(注意,这只是一个例子.我不是问什么是读取文件的最佳方法):
try
{
reader = new StreamReader(path);
}
catch (Exception)
{
// Uh oh something went wrong with opening the file for reading
}
else
{
string line = reader.ReadLine();
char character = line[30];
}
Run Code Online (Sandbox Code Playgroud)
从我在大多数C#代码中看到的,人们只会写下面的内容:
try
{
reader = new StreamReader(path);
string line = reader.ReadLine();
char character = line[30];
}
catch (Exception)
{
// Uh oh something went wrong, but where?
}
Run Code Online (Sandbox Code Playgroud)
这样做的问题在于我不希望因为文件中的第一行不能包含超过30个字符而超出范围异常.我只想捕获与读取文件流有关的异常.我可以在C#中使用任何类似的构造来实现相同的功能吗?
我想知道是否有可能在finally块中获取函数的返回值.
我有一些像这样的代码.
try
{
return 1;
}
finally
{
//Get the value 1
}
Run Code Online (Sandbox Code Playgroud)
我知道可以添加一个可以保存返回值的变量.但我想知道是否有可能以任何方式获得价值.
谢谢
我在firefox和chrome中编写了一个自调用函数,它不会调用它.
我写了一些东西到了效果
(function () { alert("THE"); })();
Run Code Online (Sandbox Code Playgroud)
自调用函数在当前浏览器中不起作用?
谢谢
编辑:我确实包含了所有必要的标签,所有其他代码都在页面上运行