final、finally、finalize的区别及异常处理

1、final,finally 和 finalize的区别
final为关键字,可修饰成员变量、成员方法、类,修饰成员变量,变量看做常量,只能修改一次;修饰成员方法,该方法不可被重写;修饰类,该类不可被继承。
finally位于try-catch异常捕获结构的最后位置,fianally中的内容一定会被执行,一般用作资源释放。
finalize为java垃圾回收的方法,当一个对象被垃圾回收器判断为无用对象时,即调用此方法。
2、定义三种新类型的异常。
写一个类,在该类的三个方法中抛出三种不同的异常。
然后在mian方法中调用这个类的不同方法,尝试用try catch捕获你写的异常。

package com.homework.homework0727;

/**
 * @Author jinman1012@qq.com   2020/7/27 19:30
 * @Version 1.0
 */
public class Problem2 {
    public static void main(String[] args) throws MyFirstExceptions {
        Exceptions exceptions = new Exceptions();
        try {
            exceptions.arrayOut();
            exceptions.nullPoint();
            exceptions.arithMetic();
            exceptions.clone();
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("ArrayIndexOutOfBoundsException");
        }catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }catch (ArithmeticException e) {
            System.out.println("ArithmeticException");
        } catch (CloneNotSupportedException e) {
            System.out.println("CloneNotSupportedException");
        }finally {
            System.out.println("finally test");
        }
        try{
            exceptions.myFirstException();
            exceptions.mySecondException();
        }catch (MyFirstExceptions |MySecondException e) {
            System.out.println("test自定义异常");
        }
    }
}
class Exceptions {
    public void arrayOut() {
        int[] arr = new int[3];
        System.out.println(arr[3]);
//        throw new ArrayIndexOutOfBoundsException("数组越界异常");
    }
    public void nullPoint() {
        int[] arr = null;
        System.out.println(arr.length);
//        throw new NullPointerException("空指针异常");
    }
    public void arithMetic() {
        int a = 10;
        int b = a / 0;
//        throw  new ArithmeticException("/ by zero");
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public void myFirstException() throws MyFirstExceptions {
        throw new MyFirstExceptions("myFirstException");
    }
    public void mySecondException() {
        throw new MySecondException("mySecondException");
    }
}

class MyFirstExceptions extends Exception {
    public MyFirstExceptions(String message) {
        super(message);
    }
}
class MySecondException extends RuntimeException {
    public MySecondException(String message) {
        super(message);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值