Custom "Invalid name exception"
1. Compile-time exception, directly inherit exception
2. Run-time exception, directly inherit RuntimeException
public class illegalnameexception extends exception{//compile-time exception//public class illegalnameexception extends runtimeexception{//run-time exception Public illegalexception () { } public illegalexception ( string msg) { super (msg); }}// Defines a consumer class Public class customerservice{ public void register (string name) throws illegalexception{ if (Name.length () <6) { //exception //Creating Exception Objects illegalexception e=new illegalexception ("User name length cannot be less than six bits"); throw e; //throw Illegalexception ("User name length cannot be less than six bits"); } //If executed here, the user name is legal. system.out.println ("User name is valid, registration is successful!") "); }}//test class public class test{ public static Void main (String[] args) { string name= "Nihao"; customerservice cs=new customerservice (); try{ cs.register (" Nihao "); }catch (illegalnameexception e) { system.out.println (E.getMessage ()); } }}
This article is from the "Gaogaozi" blog, make sure to keep this source http://hangtiangazi.blog.51cto.com/8584103/1661718
Custom Exceptions in Java (standard)