java中自定义异常类

目录

对异常不了解的点击这里

I.自定义异常

II.关于异常中的方法的覆盖问题

一、自定义异常

1.1自定义异常的格式
  • 需要继承Exception或者Exception的子类。
  • 一般常用于继承RuntimeException
  • 经常提供一个带参数message的构造方法,和一个无参构造方法,并在对应方法内用super()调用其父类构造方法
class TestException implements RuntimeException{
	// 构造方法
	public TestException(){
		super();
	}
	public TestException(String message){ 
		super(message);
	}
}
1.2自定义异常的抛出形式

UnCheck Exception 运行时异常

  • 一般来说运行时异常就是RuntimeException异常及其子类异常
  • 此类异常在声明时候可抛出也可不抛出
class TestException implements RuntimeException{
	// 构造方法
	public TestException(){
		super();
	}
	public TestException(String message){ 
		super(message);
	}
}
// 运行时异常的测试类
public class Test{
	public static void main(String[] args){
		try{
			test();
			test1();
		}catch(TestException e){
			System.err.println(e.getMessage());
		}
		
	}
	private void test(){
		throw new TestException("运行时异常的测试");
	}
	private void test1() throws TestException{
		throw new TestException("运行时异常的测试");
	}
}

Check Exception 检查异常

  • 除了RuntimeException及其子类异常其他基本都是检查异常
  • 声明:
    1. 需要声明该异常,传递出去
    2. 声明的异常类型与抛出去的异常类型一致
class TestException implements Exception{
	// 构造方法
	public TestException(){
		super();
	}
	public TestException(String message){ 
		super(message);
	}
}
// 检查期异常的测试类
public class Test{
	public static void main(String[] args){
		try{
			test();
		}catch(TestException e){
			System.err.println(e.getMessage());
		}
		
	}
	private void test() throws TestException{
		throw new TestException("检查时异常的测试");
	}
	
}

两种异常的抛出方法一样

  • 此类异常抛出时 throw new 自定义异常类名(异常提示内容)
1.3自定义异常的捕获

异常的捕获常用如下格式:

try{

}catch(){

}...
}catch(Exception e){

}
public class Test{
	public static void main(String[] args){
		try{
			test();
		}catch(TestException e){
			System.err.println(e.getMessage());
		}catch(Exception e){
		
		}
		
	}
	private void test() throws RuntimeException{
		throw new RuntimeException("运行时异常的测试");
	}
	
}

在最后添加一个Exception异常的获取,方便解决遗漏的bug异常

二、关于异常中的方法的覆盖问题

异常是继承父类的所以会有方法的覆盖。接口与父类的复写相似

对于父类/接口 中定义的异常方法,覆盖是需要注意:

  • 方法名、参数、形参列表类型必须与父类被覆盖的该方法一致
  • 子类权限访问控制符的权限必须大于等于父类方法的权限
  • 父类中方法没有声明异常则子类不能声明
  • 父类中方法声明了异常,则子类重写后可以声明也可以不声明,但是要注意对象上转型时调用回该方法要抛出父类异常
  • 子类可以声明比父类更多的异常,但必须小于等于父类异常(也就是父类异常或者其异常的子孙类)
class Parent{
	public void testMethod() throws Exception{
		System.out.println("我是父类");
		throw new Exception("我是父类");
	}
}
class Son extends Parent{
	public void testMethod() throws RuntimeException{
		System.out.println("我是子类");
		throw new RuntimeException("我是子类");
	}
}

接口中的例子

interface Perent{
	public void testMethod() throws Exception;
}
class Student{
	public void testMethod() throws RuntimeException,NullPointerException{

	}
}
发布了29 篇原创文章 · 获赞 33 · 访问量 5110

猜你喜欢

转载自blog.csdn.net/lxn1214/article/details/104781211