這篇文章主要為大家展示了如何使用Java異常處理,內(nèi)容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。
成都創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于做網(wǎng)站、成都網(wǎng)站制作、南宮網(wǎng)絡(luò)推廣、小程序設(shè)計、南宮網(wǎng)絡(luò)營銷、南宮企業(yè)策劃、南宮品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;成都創(chuàng)新互聯(lián)為所有大學生創(chuàng)業(yè)者提供南宮建站搭建服務(wù),24小時服務(wù)熱線:18982081108,官方網(wǎng)址:www.chinadenli.net
異常:

算術(shù)異常類:ArithmeticExecption
空指針異常類:NullPointerException
類型強制轉(zhuǎn)換異常:ClassCastException
數(shù)組下標越界異常:ArrayIndexOutOfBoundsException
輸入輸出異常:IOException



public class Demo {
public static void main(String[] args) {
// int a=10/0;
try{
int a=10/0;
}catch(ArithmeticException e) {
System.out.println("run in ArithmeticException "+e);
//run in ArithmeticException java.lang.ArithmeticException: / by zero
}
catch (Exception e) {
System.out.println(e);
}finally {
System.out.println("最終執(zhí)行的");//最終執(zhí)行的
}
}
}throws用于聲明異常,聲明函數(shù)可能發(fā)生的異常。【當函數(shù)中有throw來拋出異常時,函數(shù)頭必須使用throws聲明異常】
throw用于手動拋出異常,可以拋出自定義異常信息:throw 異常類型(異常信息)
public class Demo2 {
static int div(int a,int b) throws ArithmeticException{
if (b==0){
throw new ArithmeticException("發(fā)生除零異常了!");
}
return a/b;
}
public static void main(String args[]) {
try {
System.out.println(div(2,0));
}catch(ArithmeticException e) {
System.out.println(e.getMessage());//發(fā)生除零異常了!
}finally {
System.out.println("in finally");//in finally
}
System.out.println("after finally");//after finally
}
}一般對于不想在函數(shù)中處理異常時,一般采用異常拋出處理(throw throws);否則使用try…catch…finally捕獲異常。
有時候沒有定義我們想要的異常(比如我們MySQL連接異常),那么我們可以自定義異常。
class MyException extends Exception{
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public class Demo3 {
static int div(int a,int b) throws MyException {
if (b==0){
throw new MyException("發(fā)生異常了!");
}
return a/b;
}
public static void main(String args[]) {
try {
System.out.println(div(2,0));
}catch(Exception e) {
System.out.println(e);//異常.MyException: 發(fā)生除零異常了!
}
}
}
public class Demo {
public static void main(String[] args) {
Boolean food=false;
System.out.println("準備開始吃飯");
assert food;
System.out.println("飯來了");
}
}
以上就是關(guān)于如何使用Java異常處理的內(nèi)容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。
新聞標題:如何使用Java異常處理
分享鏈接:http://www.chinadenli.net/article32/iphgpc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機網(wǎng)站建設(shè)、關(guān)鍵詞優(yōu)化、微信小程序、企業(yè)建站、軟件開發(fā)、網(wǎng)站設(shè)計公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)