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);
}
}