2016-01-18 31 views
2

我不知道是否可以是那些2塊之間的差異或性能問題:捕獲異常或特定類型異常之間是否存在性能差異? - Java的

try{ 
     return Integer.parseInt(numAsString); 
    }catch (Exception e){ 
     return onErrorInt; 
    } 

try{ 
     return Integer.parseInt(numAsString); 
    }catch (NumberFormatException e){ 
     return onErrorInt; 
    } 

有時甚至有裏面嘗試了很多有點像例外:

try{ 
     // open file then try to close 
     // try to parse integer 
     // another kind of exception throwing funcitons 
    }catch (Exception e){ 
     return onErrorInt; 
    } 

and

try{ 
     // open file then try to close 
     // try to parse integer 
     // another kind of exception throwing funcitons 
    }catch (NumberFormatException e){ 
     return // something; 
    } catch (IOException e){ 
     // return same thing in the exception above 
    } 

我在做什麼是系統,將保持每天24小時運行,每天重新啓動1次。

在許多地方,我不在乎異常的類型,我只需要讓我的應用程序一直運行。所以主要是我的問題性能

+0

當你捕獲一個特定的一個,你可以專門處理它? – ChiefTwoPencils

+5

直到你證明這段代碼導致性能問題,你應該做_right_事情。現在的問題沒有意義。如果有的話,不會有任何你會注意到的。 –

+0

如果您擔心捕捉異常的性能,您可能會頻繁拋出異常,並且代碼中存在嚴重錯誤。 –

回答

9

性能差異?幾乎沒有。唯一的代價是迭代ExceptionTable,這是一個非常低調的內存操作。你可以看到這裏的內部一個簡短的總結:

JVM spec on Exception handling

的主要原因異常類型之間的區分是爲了讓開發者如果需要的話在不同類型的例外採取不同的行動。