try-catch以及try-catch-finally
語(yǔ)法:
try{ //一些會(huì)拋出異常的方法}catch(Exception e){ //處理該異常的代碼塊}finally{ //最終將要執(zhí)行的一些代碼}解釋:(1)如果try拋出異常,程序會(huì)終止執(zhí)行,程序的控制權(quán)會(huì)轉(zhuǎn)移交給catch塊中的異常處理程序
(2)try語(yǔ)句塊不可以獨(dú)立存在,必須與catch或finally塊共存
(3)用try-catch語(yǔ)句塊處理完異常還需進(jìn)行一些善后工作,比如關(guān)閉連接或關(guān)閉打開的一些文件,則用finally語(yǔ)句塊進(jìn)行善后工作
例如:
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"); } }}運(yùn)行結(jié)果:
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("請(qǐng)輸入第一個(gè)數(shù):"); int m=in.nextInt(); System.out.println("請(qǐng)輸入第二個(gè)數(shù):"); int n=in.nextInt(); System.out.println(m+"/"+n+"="+m/n); } catch(InputMismatchException e){ System.out.println("輸入類型不正確,請(qǐng)輸入整數(shù)"); } catch(ArithmeticException e){ System.out.println("除數(shù)不能為0"); } catch(Exception e){ //Exception是InputMismatchException和ArithmeticException兩個(gè)類的父類 } finally{ //最終要執(zhí)行的一些代碼 } }}運(yùn)行結(jié)果(三組數(shù)據(jù)):請(qǐng)輸入第一個(gè)數(shù):3請(qǐng)輸入第二個(gè)數(shù):0除數(shù)不能為0
請(qǐng)輸入第一個(gè)數(shù):f輸入類型不正確,請(qǐng)輸入整數(shù)
請(qǐng)輸入第一個(gè)數(shù):4請(qǐng)輸入第二個(gè)數(shù):24/2=2注意:編寫多重catch塊時(shí)要先子類后父類,如上面的代碼,Exception要寫在最后。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注