我有一段类似于此的代码:
import sys
def func1():
func2()
def func2():
raise Exception('test error')
def main():
err = None
try:
func1()
except:
err = sys.exc_info()[1]
pass
# some extra processing, involving checking err details (if err is not None)
# need to re-raise err so caller can do its own handling
if err:
raise err
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
当func2引发异常时,我收到以下回溯:
Traceback (most recent call last):
File "err_test.py", line 25, in <module>
main()
File "err_test.py", line 22, in main
raise err …Run Code Online (Sandbox Code Playgroud) 这是一个采访问题:
public class Demo {
public static void main(String[] args) {
System.out.println(foo());
}
static String foo() {
try {
return "try ...";
} catch (Exception e) {
return "catch ...";
} finally {
return "finally ..."; //got as result
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么没有编译时错误.当我在finally块中有return语句时,它必然会从而finally不是try和catch块返回.我尝试使用-Xlint选项编译此代码,它会发出警告.
warning: [finally] finally clause cannot complete normally
Run Code Online (Sandbox Code Playgroud) 寻找一些参考资料后弄明白,-unfortunately-我找不到任何关于理解之间的差异有用-和简单-描述throws和rethrows.当试图理解我们应该如何使用它时,这有点令人困惑.
我想提一下,我对-default-熟悉throws传播错误的最简单形式,如下所示:
enum CustomError: Error {
case potato
case tomato
}
func throwCustomError(_ string: String) throws {
if string.lowercased().trimmingCharacters(in: .whitespaces) == "potato" {
throw CustomError.potato
}
if string.lowercased().trimmingCharacters(in: .whitespaces) == "tomato" {
throw CustomError.tomato
}
}
do {
try throwCustomError("potato")
} catch let error as CustomError {
switch error {
case .potato:
print("potatos catched") // potatos catched
case .tomato:
print("tomato catched")
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止一直很好,但问题出现在:
func throwCustomError(function:(String) throws -> ()) throws {
try function("throws string") …Run Code Online (Sandbox Code Playgroud) 我正在构建一个从互联网上检索图像的应用程序.即使它工作正常,但在应用程序中使用try-catch语句时速度很慢(在错误的给定URL上).
(1)这是验证URL和处理错误输入的最佳方法 - 还是应该使用正则表达式(或其他方法)?
(2)如果我没有在textBox中指定http://,为什么应用程序尝试在本地查找图像?
private void btnGetImage_Click(object sender, EventArgs e)
{
String url = tbxImageURL.Text;
byte[] imageData = new byte[1];
using (WebClient client = new WebClient())
{
try
{
imageData = client.DownloadData(url);
using (MemoryStream ms = new MemoryStream(imageData))
{
try
{
Image image = Image.FromStream(ms);
pbxUrlImage.Image = image;
}
catch (ArgumentException)
{
MessageBox.Show("Specified image URL had no match",
"Image Not Found", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
catch (ArgumentException)
{
MessageBox.Show("Image URL can not be an empty string",
"Empty Field", …Run Code Online (Sandbox Code Playgroud) 有没有像linux try catch一样的linux bash命令?或者linux shell总是继续?
try {
`executeCommandWhichCanFail`
mv output
} catch {
mv log
} finally {
rm tmp
}
Run Code Online (Sandbox Code Playgroud) 好吧,这可能是一个非常noob的问题,但我发现PHP文档和几个Internet搜索没有给我任何想法.
我什么时候应该使用try-catch块来改善我的应用程序?
我读过有人说我们应该只使用try-catch块来防止致命错误.我读到其他人说我们应该只在意外错误上使用它(等待什么?意外?如果它们是意外错误我怎么能用try-catch阻止它们?我应该把所有应用程序代码放在try块中吗?).其他人只是说try-catch块应该在任何地方使用,因为它们也可以扩展(扩展Exception类).最后有人说PHP try-catch块完全没用,因为它们实现得非常糟糕.(在此我发现了一个关于性能的好问题).
在我看来,这个话题非常奇怪和困惑.有人会点亮我吗?
通过阅读本论坛中已经提到的与上述主题相关的所有问题(参见标题),我完全理解finally总是被称为.(除了System.exit和无限循环).但是,我想知道是否return在catch块中调用了a,然后return从finally块调用了另一个.
例如:
public static void main(String[]args) {
int a = new TestClass().absorbeTheValue();
}
int absorbeTheValue() {
try {
int a = 10/0;
if (a > 0) return 4;
} catch(Exception e) {
return 45;
} finally {
return 34;
}
}
Run Code Online (Sandbox Code Playgroud)
所以这里输出(当调用方法时)在任何情况下都是34.这意味着终于总能运行.我认为虽然其他"回归"根本没有运行.在很多帖子中,我发现最后将内容写入catch子句返回已写入的内容.我的理解是,一旦catch子句中的返回值即将被评估,控制流就会传递给finally子句,而子句又有另一个返回,这次返回将被评估,而不会将控制权传递给catch子句.通过这种方式,return在运行时唯一被调用的是最终返回.你同意吗?
甲return在finally不传递回控制到程序但返回值,并结束方法.我们可以这样说吗?
Long.parseLong("string")如果字符串无法解析为long,则抛出错误.有没有办法比使用更快地验证字符串try-catch?谢谢
下面有一些有趣的代码:
def func1():
try:
return 1
finally:
return 2
def func2():
try:
raise ValueError()
except:
return 1
finally:
return 3
func1()
func2()
Run Code Online (Sandbox Code Playgroud)
可以请有人解释,结果将返回这两个函数并解释原因,即描述执行的顺序
我正在使用promises并且代码如下所示:
function getStuff() {
return fetchStuff().then(stuff =>
process(stuff)
).catch(err => {
console.error(err);
});
}
Run Code Online (Sandbox Code Playgroud)
要么:
async function getStuff() {
try {
const stuff = await fetchStuff();
return process(stuff);
} catch (err) {
console.error(err);
}
}
Run Code Online (Sandbox Code Playgroud)
我这样做是为了避免错过错误但是同事用户告诉我不应该这样做而且不赞成.
return ….catch(err => console.error(err))?