java 异常Throwable / Exception

一、异常基础

package com.gongxy.demo;

/**
 * 异常测试
 * java.lang.Throwable
 *  -java.lang.Exception
 * checked异常(必须处理否则无法编译通过) / unchecked异常
 */
public class ExceptionTest {
    public static void main(String[] args) {
        testException1();
    }

    static void testException1(){
        try {
            int a = 2;
            a--;
            int b = 5 / a;
            System.out.println(b);
        }
        catch(ArithmeticException ex) {
            //打印异常
            ex.printStackTrace();
            System.out.println("error");
        }
        finally {
            System.out.println("finally");
        }
    }

    /**
     * 抛出异常给方法的调用者处理
     * @throws Exception
     */
    static  void testException2() throws Exception{
        try {
            int a = 1;
            a--;
            int b = 5 / a;
            System.out.println(b);
        }
        catch(Exception ex) {
            throw new Exception("除数为0");
        }
    }
}

  

二、自定义异常

package com.gongxy.demo;

/**
 * 自定义异常
 * 编写java继承任意异常类即可
 * 异常类也是一个普通的java类,可以定义成员变量和方法
 */
public class MyException extends RuntimeException {
}

  

posted @ 2020-08-08 00:42  gygtech  Views(180)  Comments(0Edit  收藏  举报