国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

try-catch以及try-catch-finally

2019-11-14 11:41:14
字體:
來源:轉載
供稿:網友

try-catch以及try-catch-finally

語法:

try{	//一些會拋出異常的方法}catch(Exception e){	//處理該異常的代碼塊}finally{	//最終將要執行的一些代碼}解釋:

(1)如果try拋出異常,程序會終止執行,程序的控制權會轉移交給catch塊中的異常處理程序

(2)try語句塊不可以獨立存在,必須與catch或finally塊共存

(3)用try-catch語句塊處理完異常還需進行一些善后工作,比如關閉連接或關閉打開的一些文件,則用finally語句塊進行善后工作

例如:

import java.util.InputMismatchException;import java.util.Scanner;public class Exception{	public static void main(String[] args) {		Scanner in=new Scanner(System.in);		try{			int m=in.nextInt();			int n=in.nextInt();			System.out.PRintln("Sum is "+(m+n));		}		catch(InputMismatchException e){			System.out.println("Incorrect input and re-enter two integers");		}	}}

運行結果:

i 8Incorrect input and re-enter two integers

try拋出多種類型的異常:

例如:

public class ExceptionTest{	public static void main(String[] args) {		Scanner in=new Scanner(System.in);		try{			System.out.println("請輸入第一個數:");			int m=in.nextInt();			System.out.println("請輸入第二個數:");			int n=in.nextInt();			System.out.println(m+"/"+n+"="+m/n);		}		catch(InputMismatchException e){			System.out.println("輸入類型不正確,請輸入整數");		}		catch(ArithmeticException e){			System.out.println("除數不能為0");		}		catch(Exception e){			//Exception是InputMismatchException和ArithmeticException兩個類的父類		}		finally{			//最終要執行的一些代碼		}	}}運行結果(三組數據):

請輸入第一個數:3請輸入第二個數:0除數不能為0

請輸入第一個數:f輸入類型不正確,請輸入整數

請輸入第一個數:4請輸入第二個數:24/2=2注意:編寫多重catch塊時要先子類后父類,如上面的代碼,Exception要寫在最后。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 遵义县| 农安县| 肇庆市| 景宁| 宁都县| 沾益县| 鄱阳县| 禄丰县| 高阳县| 永春县| 邮箱| 乐业县| 盐山县| 三门县| 舒城县| 永泰县| 西宁市| 兴业县| 介休市| 灵台县| 越西县| 芦溪县| 鄂州市| 香港| 勃利县| 青阳县| 潢川县| 汝阳县| 延长县| 彰化县| 海林市| 金湖县| 淮南市| 扎鲁特旗| 淮北市| 南澳县| 沙坪坝区| 枣阳市| 揭西县| 瑞金市| 泰来县|