写一个简单自定义异常

    技术2022-07-13  75

    写一个简单自定义异常

    首先创建实例User类

    public class User { String name; int age; public User() { } public User(String name,int age) { this.name=name; this.age=age; } @Override public String toString() { return name + ":" + age ; } }

    自定义一个异常类UserException继承Exception

    public class UserException extends Exception { private static final long serialVersionUID = 1L; public UserException() { super(); // TODO Auto-generated constructor stub } public UserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public UserException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public UserException(String message) { super(message); // TODO Auto-generated constructor stub } public UserException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }

    编写异常消息

    public class UserDao { public void saveUser(User user) throws UserException{ //假设已存在name=a age=20的数据 if(user.toString().equals("a:20")) { throw new UserException("已存在"); } System.out.println("储存成功"); } }

    写一个测试类

    public class UserService extends UserException{ private static final long serialVersionUID = 1L; UserDao ud = new UserDao(); public static void main(String[] args) throws UserException { //这里写一个已经存在的数据让程序抛异常 User user = new User("a",20); UserService s = new UserService(); s.updateUser(user); } public void updateUser(User user) throws UserException { ud.saveUser(user); } }

    结果:

    Processed: 0.010, SQL: 9