相关疑难解决方法(0)

我为什么不在"尝试" - "捕获"中包裹每个块?

我一直认为,如果一个方法可以抛出一个异常,那么不顾及用一个有意义的try块来保护这个调用.

我刚刚发布了' 你应该总是包装可以抛出try,catch块的调用.'对这个问题,并被告知这是'非常糟糕的建议' - 我想明白为什么.

c++ java exception-handling exception try-catch

424
推荐指数
11
解决办法
6万
查看次数

try/catch语句中有多少个语句?

我应该在try中放入多个语句然后捕获所有可能的异常,还是应该只在try语句中放入一个语句?

例:

try {
    MaybeThrowIOException();
    MaybeThrowFooBarException();
    return true;
} catch (IOException e) {
    // ...
} catch (FooBarException e) {
   // ... 
}
Run Code Online (Sandbox Code Playgroud)

要么

try {
    MaybeThrowIOException();
} catch (IOException e) {
    // ...
}

try {
    MaybeThrowFooBarException();
} catch (FooBarException e) {
   // ... 
}

return true;
Run Code Online (Sandbox Code Playgroud)

oop exception-handling exception try-catch

7
推荐指数
1
解决办法
3388
查看次数

Java:输入/使用"try-catch"块的开销?

问题就是这一切.虽然命中率不是很高(我测量它的速度在1.5x到2x之间),但是try-catch的字节代码与没有try-catch的字节代码之间没有区别.那么是什么让它通常变慢?

PL.请注意,问题不在于抛出异常的开销,而在于进入/离开try块.

编辑:这是代码(在Hotspot 1.6.0_31服务器上运行)

static void tryCatch()
{
    int i = 0;
    long l1 = getTime();
    for(int j = 0; j < 100000; j++)
    {
        try
        {
            i++;                
        }
        catch(Exception e)
        {

        }
    }
    long l2 = getTime();
    System.out.println("with try-catch: " + (l2 - l1) + ": " + i);      
}

static void noTryCatch()
{
    int i = 0;
    long l1 = getTime();
    for(int j = 0; j < 100000; j++)
    {
        i++;
    }
    long l2 = getTime();
    System.out.println("w/o  try-catch: …
Run Code Online (Sandbox Code Playgroud)

java performance jvm try-catch

3
推荐指数
1
解决办法
2731
查看次数

标签 统计

try-catch ×3

exception ×2

exception-handling ×2

java ×2

c++ ×1

jvm ×1

oop ×1

performance ×1