1. 程式人生 > 實用技巧 >異常處理機制

異常處理機制

機制就是丟擲 - 處理

u最基礎的處理結構:try catch 程式碼塊

package com.xuyifan.oop.demo11;

/**
 * @author xyf
 * @create 2020-08-17-15:17
 */
public class Test2 {
    public static void main(String[] args) {
        int a=0;
        int b=0;
        try{//監控區域,只要是該模組裡的程式碼
            System.out.println(a/b);

        }catch (ArithmeticException e) {
            
//cath區域捕獲的程式碼,如果出現了引數指定的的異常,就會執行catch程式碼模組 System.out.println("程式出現異常"); }finally { //不管如何,finally一定會被執行,可有可無 System.out.println("finally"); } } }

層層遞進,由小到大捕獲異常並處理

package com.xuyifan.oop.demo11;

/**
 * @author xyf
 * @create 2020-08-17-15:17
 */
public
class Test2 { public static void main(String[] args) { int a=0; int b=0; try{//監控區域,只要是該模組裡的程式碼 //System.out.println(a/b); new Test2().b(); }catch (ArithmeticException e) { //cath區域捕獲的程式碼,如果出現了指定的異常,就會執行catch程式碼模組 System.out.println("程式出現異常"); }
catch (Exception e){ System.out.println("Exception"); }catch (Throwable throwable){ System.out.println("Throwable");//層層遞進,從小到大捕獲異常 } finally { //不管如何,finally一定會被執行,可有可無 System.out.println("finally"); } } public void a(){ b(); } public void b(){ a(); } }

IDEA快捷鍵

選中需要監視的程式碼,ctrl+alt+t

關鍵字 throw 當我們肯定再某種情況下一定出問題時,我們可以用throw主動丟擲異常

try {
            if (b==0){
                throw new ArithmeticException();
            }
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

關鍵字 throws 主要用在方法上,處理不了時,主動向上丟擲異常

出現了意料中的異常,可以不讓程式停止,而是利用try catch捕獲並處理讓程式繼續執行