Java学习日记day03:异常练习题

自定义异常

问题:自定义一个异常并测试,功能随便

要求:异常类型为编译时异常

下面是我所编写的异常源码

功能:注册时用户输入用户名少于7位时抛出异常

Illegible.java文件
package com.jvstudy.day03.text3;

public class Illegible extends Exception {
	/**
	 * 自定义异常
	 * 抛出异常
	 */
	private static final long serialVersionUID = 1L;
	public Illegible() {
		
	}
	public Illegible(String mesg) {
		super(mesg);
	}

}

IllegibleService.java文件
package com.jvstudy.day03.text3;

public class IllegibleService {
	/**
	 * 自定义异常服务
	 * 功能:判断字符串长度是否小于7
	 */
	public IllegibleService(String username) throws Illegible {
		if(username.length()<=6) {
			throw new Illegible("The character length is less than 6");
		}
		System.out.println("注册成功");
	}

}
测试
package com.jvstudy.day03.text3;

import java.util.Scanner;
/**
 * 用户注册测试
 * @author hm
 *
 */
public class test1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		@SuppressWarnings("resource")
		Scanner username = new Scanner(System.in);
		System.out.println("请输入用户名:");
		try {
			new IllegibleService(username.next());
		} catch (Illegible e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

你可能感兴趣的:(Java)