面試官問我:try catch 應(yīng)該在 for 循環(huán)里面還是外面?
共 5537字,需瀏覽 12分鐘
·
2024-08-16 07:38
閱讀本文大概需要 4 分鐘。
來自:blog.csdn.net/qq_35387940/article/details/128406626
前言
正文
-
使用場景 -
性能分析 -
個人看法
使用場景
① try catch 在 for 循環(huán) 外面
public static void tryOutside() {
try {
for (int count = 1; count <= 5; count++) {
if (count == 3) {
//故意制造一下異常
int num = 1 / 0;
} else {
System.out.println("count:" + count + " 業(yè)務(wù)正常執(zhí)行");
}
}
} catch (Exception e) {
System.out.println("try catch 在for 外面的情形, 出現(xiàn)了異常,for循環(huán)顯然被中斷");
}
}
try catch 在 for 循環(huán) 外面 的時候, 如果 for循環(huán)過程中出現(xiàn)了異常, 那么for循環(huán)會終止。
② try catch 在 for 循環(huán) 里面
public static void tryInside() {
for (int count = 1; count <= 5; count++) {
try {
if (count == 3) {
//故意制造一下異常
int num = 1 / 0;
} else {
System.out.println("count:" + count + " 業(yè)務(wù)正常執(zhí)行");
}
} catch (Exception e) {
System.out.println("try catch 在for 里面的情形, 出現(xiàn)了異常,for循環(huán)顯然繼續(xù)執(zhí)行");
}
}
}
try catch 在 for 循環(huán) 里面 的時候, 如果 for循環(huán)過程中出現(xiàn)了異常,異常被catch抓掉,不影響for循環(huán) 繼續(xù)執(zhí)行。
性能
Runtime runtime = Runtime.getRuntime();
long memory = runtime.freeMemory();
也就是說, try catch 放在 for 循環(huán)里面 ,因為出現(xiàn)異常不會終止 for循環(huán)。所以如果真的存在大批量業(yè)務(wù)處理全是異常,有那么一定的內(nèi)存消耗情況。
-
Exception table: 當前函數(shù)程序代碼編譯涉及到的異常; -
type:異常類型; -
target:表示異常的處理起始位; -
from:表示 try-catch 的開始地址; -
to:表示 try-catch 的結(jié)束地址;
3. 個人看法
推薦閱讀:
SpringBoot異步接口實現(xiàn):提高系統(tǒng)的吞吐量
實用指南:解決 SpringBoot 多實例內(nèi)存不足問題
程序員在線工具站:cxytools.com 推薦一個自己寫的工具站:http://cxytools.com,專為程序員設(shè)計,包括時間日期、JSON處理、SQL格式化、隨機字符串生成、UUID生成、文本Hash...等功能,提升開發(fā)效率。
?戳閱讀原文直達! 朕已閱 ![]()
評論
圖片
表情
