異常try?catch的常見四類方式(案例代碼)
更新時間:2023年05月06日 11:52:18 作者:云棲之家
這篇文章主要介紹了異常try?catch的常見四類方式,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
第1類:嵌套模式
package day14;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class Demo0301多個異常異常的嵌套 {
public static void main(String[] args) {
String str=null;
try {
//多個異常的處理方式一:異常嵌套
try {
//str為null,有可能會報空指針異常;
InputStream is=new FileInputStream(str);
} catch (NullPointerException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}第二類:分而治之方式
package day14;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class Demo0302多個異常異常的分別處理 {
public static void main(String[] args) {
String str = null;
try {
//多個異常的處理方式一:異常嵌套
InputStream is = new FileInputStream(str);
//針對不同的異常,我分來來處理;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}第三類:異常合并方式
package day14;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class Demo0303多個異常異常的合并分開處理 {
public static void main(String[] args) {
String str = null;
try {
//多個異常的處理方式一:異常嵌套
InputStream is = new FileInputStream(str);
//針對不同的異常,捕獲的時候,合并到一起,處理的時候,分開;
} catch (NullPointerException | FileNotFoundException e){
if(e instanceof NullPointerException){
System.out.println("空指針異常");
}else if(e instanceof FileNotFoundException){
System.out.println("文件沒有找到");
}
}
}
}第四類:大合并方式
package day14;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class Demo0304多個異常異常的合并一次處理 {
public static void main(String[] args) {
String str = null;
try {
//多個異常的處理方式一:異常嵌套
InputStream is = new FileInputStream(str);
//針對不同的異常,捕獲的時候,合并到一起,處理的時候,一起處理;
} catch (Exception e){
System.out.println("異常的原因:"+e.getMessage());
}
}
}到此這篇關于異常try catch的常見四類方式的文章就介紹到這了,更多相關異常try catch內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot基于Redis實現(xiàn)生成全局唯一ID的方法
在項目中生成全局唯一ID有很多好處,生成全局唯一ID有助于提高系統(tǒng)的可用性、數(shù)據的完整性和安全性,同時也方便數(shù)據的管理和分析,所以本文給大家介紹了SpringBoot基于Redis實現(xiàn)生成全局唯一ID的方法,文中有詳細的代碼講解,需要的朋友可以參考下2023-12-12
解決IntelliJ IDEA創(chuàng)建spring boot無法連接http://start.spring.io/問題
這篇文章主要介紹了解決IntelliJ IDEA創(chuàng)建spring boot無法連接http://start.spring.io/問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
spring mvc中的@PathVariable獲得請求url中的動態(tài)參數(shù)
本文主要介紹了spring mvc中的@PathVariable獲得請求url中的動態(tài)參數(shù)的代碼。具有很好的參考價值,下面跟著小編一起來看下吧2017-02-02

