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要寫在最后。
新聞熱點
疑難解答