.定义一个Student类,要求如下: 属性:id、name; 方法:构造方法,set和get方法,其中setid(String id)若id长度大于10,则抛出LengthException,若id中含有字母字符,则抛出LetterException 。 编写自定义LengthException和LetterException异常类。 编写Student类。在setid方法体中抛出LengthException或LetterException异常类 编写类ExceptionTest3:
时间: 2024-03-06 15:47:44 浏览: 21
好的,以下是定义的Student类以及自定义的LengthException和LetterException异常类的代码实现:
```java
// LengthException 自定义异常类
class LengthException extends Exception {
public LengthException(String message) {
super(message);
}
}
// LetterException 自定义异常类
class LetterException extends Exception {
public LetterException(String message) {
super(message);
}
}
// Student 类
class Student {
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) throws LengthException, LetterException {
if (id.length() > 10) {
throw new LengthException("id长度不能大于10!");
}
if (id.matches(".*[a-zA-Z]+.*")) {
throw new LetterException("id中不能含有字母字符!");
}
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// ExceptionTest3 类
public class ExceptionTest3 {
public static void main(String[] args) {
Student stu = new Student("1234567890", "张三");
try {
stu.setId("1234567890A"); // 抛出 LetterException 异常
//stu.setId("12345678901"); // 抛出 LengthException 异常
} catch (LengthException e) {
e.printStackTrace();
} catch (LetterException e) {
e.printStackTrace();
}
}
}
```
在 main 方法中创建了一个 Student 对象,然后调用 setId 方法设置 id 属性,如果输入的 id 长度大于 10 或者含有字母字符,就会抛出对应的异常。在这里我们可以通过 try-catch 语句块来捕获这些异常,并进行相应的处理。