Java基礎(chǔ)異常處理代碼及原理解析
這篇文章主要介紹了java基礎(chǔ)異常處理代碼及原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
異常的定義:中斷了正常指令流的事件。
try..catch..finally結(jié)構(gòu):
class Test{
public static void main(String[] args){
System.out.println(1);
try{
System.out.println(2);
int i = 1 / 0;
System.out.println(3);
}
catch(Exception e){
e.printStackTrace();
System.out.println(4);
}
finally{
System.out.println(5);
}
System.out.println(6);
}
}
輸出結(jié)果:
D:\Java\code\練習(xí)十二>java Test
java.lang.ArithmeticException: / by zero
at Test.main(Test.java:6)
throw與throws關(guān)鍵字
class User{
private int age;
public void setAge(int age) throws Exception{
if(age <= 0){
Exception e = new Exception("input age is error!");
throw e;
}
else{
this.age=age;
}
}
}
class Test{
public static void main(String[] args){
User u = new User();
try{
u.setAge(-20);
}
catch(Exception e){
System.out.println(e);
}
}
}
D:\Java\code\練習(xí)十二>java Test java.lang.Exception: input age is error!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot實現(xiàn)快遞物流查詢功能(快遞鳥)
本文將基于springboot2.4.0實現(xiàn)快遞物流查詢,物流信息的獲取通過快遞鳥第三方實現(xiàn),本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-10-10
java并發(fā)學(xué)習(xí)之BlockingQueue實現(xiàn)生產(chǎn)者消費(fèi)者詳解
這篇文章主要介紹了java并發(fā)學(xué)習(xí)之BlockingQueue實現(xiàn)生產(chǎn)者消費(fèi)者詳解,具有一定參考價值,需要的朋友可以了解下。2017-11-11
eclipse 如何創(chuàng)建 user library 方法詳解
這篇文章主要介紹了eclipse 如何創(chuàng)建 user library 方法詳解的相關(guān)資料,需要的朋友可以參考下2017-04-04
springboot3環(huán)境隔離的實現(xiàn)
在開發(fā)中,環(huán)境很多,本文主要介紹了springboot3環(huán)境隔離的實現(xiàn),能夠快速切換開發(fā)、測試、生產(chǎn)環(huán)境,具有一定的參考價值,感興趣的可以了解一下2024-03-03

