Java学习14

192 阅读2分钟

「这是我参与11月更文挑战的第14天,活动详情查看:2021最后一次更文挑战」。 异常处理

程序员查错网站stackoverflow.com/

程序异常处理关键字:try、catch、finally、throw、throws

1、异常的处理流程;

2、异常的处理格式;

3、异常处理的模型。

//程序异常
public class Day14 {
    public static void main(String[] args) {
        System.out.println("开始");
        try {
            System.out.println("运行"+(10/0));
        }catch (ArithmeticException e){
         e.printStackTrace();
        }
        System.out.println("结束");
    }
}
//程序异常
public class Day14 {
    public static void main(String[] args) {
        System.out.println("开始");
        try {
            System.out.println("运行"+(10/0));
        }catch (ArithmeticException e){
         e.printStackTrace();
        }finally {
            System.out.println("finally");
        }
        System.out.println("结束");
    }
}
class MyMath{
    //此处明确告诉用户该方法上会有异常
    public static int div(int x,int y)throws Exception{
        return x/y;
    }
}
public class Test21 {
    public static void main(String[] args) {
        try {
            System.out.println(MyMath.div(10,0));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
//程序员查错网站http://stackoverflow.com/
//自定义错误
class AddException extends Exception{
    public AddException(String msg){
        super(msg);
    }
}
public class Test23 {
    public static void main(String[] args) throws Exception{
        if ((10+20) == 30){
            throw new AddException("错误的相加操作!");
        }
    }
}

== 30){ throw new AddException("错误的相加操作!"); } } }

No. | 方法名称                              | 类型 | 描述              |
| --- | --------------------------------- | -- | --------------- |
| 01  | public Object()                   | 构造 | 无参构造是专门为子类提供服务的 |
| 02  | public string toString()          | 普通 | 取得对象信息          |
| 03  | public boolean equals(Object obj) | 普通 | 对象比较            |

-   Object可以接收接口更是Java中的强制性要求,因为接口本身不继承任何类的,所以这种的类型的接收就是自己的规定。
-   如果一个类希望可以接收所有的数据类型,就使用Object完成。

\
--- | ---- | --------------------------- | ---------------------------------- |
| No. | 区别   | 抽象类                         | 接口                                 |
| 1   | 关键字  | abstract class 类名称{}        | interface接口名称                      |
| 2   | 结构组成 | 抽象方法、普通方法、全局常量、全局变量、属性、构造方法 | 抽象方法和全局常量                          |
| 3   | 权限   | 可以使用各种权限                    | 只能使用public访问权限                     |
| 4   | 子类使用 | 子类利用extends关键字来继承抽象类        | 子类利用implements关键字来实现接口             |
| 5   | 关系   | 一个抽象类可实现若干个接口               | 一个接口不能够继承抽象类,但是可以使用extends来继承多个父接口 |
| 6   | 子类限制 | 一个子类只能继承一个抽象类               | 一个子类可以实现多个接口                       |

-   除了单继承的局限之外,实际上使用接口和抽象类都是类似的,但是在实际的开发之中,抽象类的设计要比接口复杂。
-   结构体:类、对象、抽象类、接口,那么这几者的具体关系可通过下图描述。
-   接口是Java的核心
-   开发过程中优先考虑接口,避免单继承局限。