第三次学JAVA再学不好就吃翔(part98)--自定义异常类

学习笔记,仅供参考,有错必纠


自定义异常类


自定义异常需要继承Exception或者是RuntimeException,如果我们的自定义异常类继承了Exception,则在方法上需要进行声明,如果我们的自定义异常类继承了RuntimeException,那么我们就不需要再方法上进行声明。


  • 举个例子

继承Exception的自定义异常类:

package com.guiyang.restudy3;

public class D8Exception {

	public static void main(String[] args) {
		Bunny b1 = new Bunny();
		
		try {
			b1.setAge(-10);
		} catch (AgeOutException e) {
			System.out.println(e.getMessage());
		}
	}
}

class AgeOutException extends Exception {
	//Alt + Shift + s 再加 c

	public AgeOutException() {
		super();
	}

	public AgeOutException(String message) {
		super(message);
	}
}

class Bunny {
	private int age;

	public Bunny() {
		super();
	}

	public Bunny(int age) {
		super();
		this.age = age;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) throws AgeOutException {
		if (age > 0 && age <= 20) {
			this.age = age;
		} else {
			AgeOutException aoe = new AgeOutException("年龄不合法!");
			throw aoe;
		}
	}
}

输出:

年龄不合法!

继承RuntimeException的自定义异常类:

package com.guiyang.restudy3;
public class D8Exception {

	public static void main(String[] args) {
		Bunny b1 = new Bunny();
		
		try {
			b1.setAge(-10);
		} catch (AgeOutException e) {
			System.out.println(e);
		}
	}
}

class AgeOutException extends RuntimeException {
	//Alt + Shift + s 再加 c

	public AgeOutException() {
		super();
	}

	public AgeOutException(String message) {
		super(message);
	}
}

class Bunny {
	private int age;

	public Bunny() {
		super();
		
	}
	
	public Bunny(int age) {
		super();
		this.age = age;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		if (age > 0 && age <= 20) {
			this.age = age;
		} else {
			AgeOutException aoe = new AgeOutException("年龄不合法!");
			throw aoe;
		}
	}
}

输出:

com.guiyang.restudy3.AgeOutException: 年龄不合法!

异常注意事项


  • 异常注意事项
    • 子类重写父类方法时,子类的方法必须抛出与父类相同的异常或父类异常的子类。
    • 如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常。
    • 如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws
  • 如何使用异常处理
    • 原则:如果该功能内部可以将问题处理,用try,如果处理不了,则用throws

    • 区别

      • 后续程序需要继续运行就try
      • 后续程序不需要继续运行就throws
    • 如果JDK没有提供对应的异常,需要自定义异常。

猜你喜欢

转载自blog.csdn.net/m0_37422217/article/details/107454228