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

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

try-catch以及try-catch-finally

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

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要寫在最后。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 博罗县| 延长县| 始兴县| 湖南省| 上蔡县| 河间市| 公主岭市| 雷山县| 永靖县| 文山县| 东兴市| 从江县| 抚州市| 嘉义市| 田阳县| 岗巴县| 沙河市| 盐亭县| 秦安县| 上饶县| 惠来县| 长治市| 讷河市| 青冈县| 威海市| 宜良县| 沅江市| 永善县| 通州市| 扎赉特旗| 忻州市| 孟州市| 肃北| 和平县| 内江市| 黑水县| 曲松县| 尼玛县| 蒙山县| 伊金霍洛旗| 洛南县|