相关疑难解决方法(0)

即使从不抛出异常,使用try-catch块是否昂贵?

我们知道捕获异常是昂贵的.但是,即使从未抛出异常,在Java中使用try-catch块也是昂贵的吗?

我发现Stack Overflow问题/答案为什么尝试块昂贵?,但它适用于.NET.

java performance try-catch

181
推荐指数
7
解决办法
4万
查看次数

35
推荐指数
6
解决办法
1万
查看次数

Java try/catch性能,是否建议将try子句中的内容保持在最低限度?

考虑到你有这样的代码:

doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
Run Code Online (Sandbox Code Playgroud)

现在我知道,实际上在构造异常时会出现性能损失,特别是展开堆栈.我还阅读了几篇文章,指出在输入try/catch块时会有轻微的性能损失,但这些文章似乎都没有结论.

我的问题是,是否建议将try catch中的行保持最小?,即只在try子句中包含可以实际抛出正在捕获的异常的行.try子句中的代码运行速度较慢或导致性能下降吗?

但考虑到这一点,更重要的是最佳实践/更易读的解决方案:

try {
    doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing …
Run Code Online (Sandbox Code Playgroud)

java performance readability try-catch

33
推荐指数
2
解决办法
2万
查看次数

使用try/catch而不是多个IF语句更好吗?

try/catch在Java中使用块而不是使用多个If语句来检查用户输入是否更好,更便宜或更具可读性?

解析Date字符串时的示例,使用try/catch块直接解析而不是编写查找非法字符的多个语句不是更好.

在另一个例子中,假设我想要读取文件或流,而不是使用Scanner,我只是强制该方法并等待发生异常.

这是一种健康的编程方法吗?它在虚拟机上更便宜吗?

更新
这里是我在使用DateFormat异常时的意思的一个例子,有时它可能是一个真正的问题来捕获错误,并且这样做,你能保证你的复杂(通常是不可读)代码容易出错吗?

java try-catch

14
推荐指数
1
解决办法
6730
查看次数

尝试Catch Performance Java

捕获异常而不是进行检查时,try-catch需要多长时间(以纳秒为单位)(假设消息具有HashMap类型的查找性能)?

    try {
        timestamp = message.getLongField( MessageField.TIMESTAMP );
    } catch (MissingDataException e) {
        //Not all messages contain this field
    }
Run Code Online (Sandbox Code Playgroud)

VS

if (message.contains(MessageField.TIMESTAMP))
    timestamp = message.getLongField( MessageField.TIMESTAMP );
Run Code Online (Sandbox Code Playgroud)

java performance try-catch

6
推荐指数
1
解决办法
7392
查看次数

Java尝试捕获块

这是一个简单的问题:

您如何看待每次使用try catch的代码?

void myfunction() {
    try {
        instruction1();
    }
    catch (ExceptionType1 e) {
        // some code
    }
    try {
        instruction2();
    }
    catch (ExceptionType2 e) {
        // some code
    }
    try {
        instruction3();
    }
    catch (ExceptionType3 e) {
        // some code
    }
    try {
        instruction4();
    }
    catch (ExceptionType4 e) {
        // some code
    }

    // etc
}
Run Code Online (Sandbox Code Playgroud)

我知道这太可怕了,但我想知道这是否会降低性能.

java try-catch

5
推荐指数
3
解决办法
7985
查看次数

标签 统计

java ×6

try-catch ×6

performance ×3

if-statement ×1

readability ×1