在使用Eclipse中的自定义格式选项时,在其中一个示例代码中,我看到了如下代码:
/**
* 'try-with-resources'
*/
class Example {
void foo() {
try (FileReader reader1 = new FileReader("file1"); FileReader reader2 = new FileReader("file2")) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
我从来没有见过这样的try用法,我已经用Java编写了9年!有人知道你为什么要这样做吗?这样做的用例/好处是什么?
我看到的其他代码片段,我认为这是一个非常有用的简写,所以我也在这里分享它,它的作用非常明显:
/**
* 'multi-catch'
*/
class Example {
void foo() {
try {
} catch (IllegalArgumentException | NullPointerException | ClassCastException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud) 我在try块中的代码有问题.为了方便起见,这是我的代码:
try:
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
except:
pass
Run Code Online (Sandbox Code Playgroud)
这样的事情可能吗?
我正在为已经存在了很长时间的应用程序编写单元测试.我需要测试的一些方法是这样构建的:
public void someMethod() throws Exception {
//do something
}
Run Code Online (Sandbox Code Playgroud)
如果我想测试这些方法,我必须在单元测试中写这样的东西:
@Test
public void someTest() {
try {
someMethod();
}
catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
这样做是一种好习惯吗?或者还有其他方法来测试这些方法吗?
我在互联网上做了一些研究,我找到了一些带@Rule注释的解决方案@Test(expected=Exception.class),但是这不起作用(Eclipse不断someMethod()将测试中的行显示为错误).我不知道这些是不是很好的解决方案,因为我对整个单元测试故事都很陌生.
如果对此有很多了解的人可以帮助我,我会非常感激.
只是好奇:为什么C#中的try catch语法(Java也?)为多个语句硬编码?为什么语言不允许:
int i;
string s = DateTime.Now.Seconds % 2 == 1 ? "1" : "not 1";
try
i = int.Parse(s);
catch
i = 0;
Run Code Online (Sandbox Code Playgroud)
这个例子只是为了琐碎的目的.我知道有int.TryParse.
当没有任何异常被抛出时,使用几个try-catch块是"慢"吗?我的问题与此问题相同,但对于Javascript.
假设我有20个函数,其中包含try-catch块.另一个函数调用这20个函数中的每一个.他们都不会抛出异常.由于这个try-catch块,我的代码执行速度会慢还是执行得更差?
javascript performance exception-handling exception try-catch
在阅读我的代码时,我注意到我的IDE列出了一条警告,其中包含以下消息:
在JDK 7下的try块中报告相同的catch部分.可以使用quickfix将部分折叠为multi-catch部分.
并且还指定为JDK 7+抛出此警告
try块如下:
try {
FileInputStream e = new FileInputStream("outings.ser");
ObjectInputStream inputStream = new ObjectInputStream(e);
return (ArrayList)inputStream.readObject();
} catch (FileNotFoundException var3) {
var3.printStackTrace();
} catch (ClassNotFoundException var5) {
var5.printStackTrace();
} catch (IOException ex){
ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
但是当删除时(抛出该特定警告的catch块):
catch (ClassNotFoundException var5) {
var5.printStackTrace();
} catch (IOException ex){
ex.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我仍会得到错误:
ObjectInputStream inputStream = new ObjectInputStream(e);
return (ArrayList)inputStream.readObject();
Run Code Online (Sandbox Code Playgroud)
我错过了一些我到目前为止还没想到的明显的东西吗?
如果发生异常,我有一些我想要执行的代码.但该代码也可以生成异常.但我从未见过人们在另一个try/catch中尝试/捕获.
我正在做不好的练习,也许还有更好的方法:
Uri uri = Uri.parse("some url");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
startActivity(intent);
}
catch (ActivityNotFoundException anfe)
{
// Make some alert to me
// Now try to redirect them to the web version:
Uri weburi = Uri.parse("some url");
try
{
Intent webintent = new Intent(Intent.ACTION_VIEW, weburi);
startActivity(webintent);
}
catch ( Exception e )
{
// Make some alert to me
}
}
Run Code Online (Sandbox Code Playgroud)
这看起来有点尴尬.有什么东西可能有问题吗?
我正在关注Coursera的Scala课程.我也开始阅读Odersky的Scala书.
我经常听到的是,在函数式语言中抛出异常并不是一个好主意,因为它会破坏控制流,我们通常会返回一个带有失败或成功的Either.似乎Scala 2.10也将提供那个方向的Try.
但是在书和课程中,马丁奥德斯基似乎并没有(至少现在)说异常是坏的,而且他经常使用它们.我也注意到方法断言/要求......
最后我有点困惑,因为我想遵循最佳实践,但他们不清楚,语言似乎是双向的...
有人可以解释一下我应该在哪种情况下使用什么?
在交互式提示符(REPL)上调试Python代码时,我经常会编写一些引发异常的代码,但是我没有将它包装在try/中except,所以一旦引发错误,我就永远丢失了异常对象.
通常Python打印出来的追溯和错误消息是不够的.例如,在获取URL时,服务器可能会返回40x错误,并且您需要通过error.read()... 的响应内容,但您还没有得到错误对象.例如:
>>> import urllib2
>>> f = urllib2.urlopen('http://example.com/api/?foo=bad-query-string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
urllib2.HTTPError: HTTP Error 400: Bad Request
Run Code Online (Sandbox Code Playgroud)
Drat,回应的主体说了什么?它可能包含有价值的错误信息......
我意识到重新运行包含在try/except中的代码通常很容易,但这并不理想.我也意识到在这种特殊情况下,如果我使用的是requests库(不会引起HTTP错误),我就不会有这个问题...但我真的很想知道是否有更通用的方法来获取在这些情况下,Python提示符下的最后一个异常对象.
我喜欢Async/Await在Typescript等中提供的新功能的平坦性.但是,我不确定我喜欢这样一个事实,即我必须await在try...catch块的外部声明变量才能在以后使用它.像这样:
let createdUser
try {
createdUser = await this.User.create(userInfo)
} catch (error) {
console.error(error)
}
console.log(createdUser)
// business
// logic
// goes
// here
Run Code Online (Sandbox Code Playgroud)
如果我错了,请纠正我,但似乎最好不要在机构中放置多行业务逻辑try,所以我只留下createdUser在块外声明,在块中分配它的替代方案,以及然后用它.
在这种情况下,最佳做法是什么?
try-catch ×10
exception ×5
java ×4
javascript ×2
python ×2
async-await ×1
c# ×1
either ×1
except ×1
junit ×1
performance ×1
promise ×1
scala ×1
syntax ×1
unit-testing ×1