java3.自定义异常类,输入一个邮箱,用正则表达式判断其合法性,若不合法,则抛 出自定义异常。
时间: 2024-05-15 08:17:25 浏览: 11
好的,我会为你回答这个问题。以下是Java代码示例:
```java
public class EmailFormatException extends Exception {
public EmailFormatException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void validateEmail(String email) throws EmailFormatException {
String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
if (!email.matches(regex)) {
throw new EmailFormatException("Invalid email format!");
}
}
public static void main(String[] args) {
String email = "test@example";
try {
validateEmail(email);
System.out.println("Valid email!");
} catch (EmailFormatException e) {
System.out.println(e.getMessage());
}
}
}
```
在上面的示例中,我们定义了一个自定义异常类 `EmailFormatException`,它继承自 Java 内置异常类 `Exception`。然后,我们编写了一个静态方法 `validateEmail`,它接受一个字符串参数 `email`,并使用正则表达式验证它是否是一个有效的 email 地址。如果 `email` 不合法,则抛出我们刚刚定义的自定义异常类型 `EmailFormatException`。
在 `main` 方法中,我们调用 `validateEmail` 方法,将 `test@example` 作为参数传递给它。由于 `test@example` 不是一个有效的 email 地址,因此方法抛出 `EmailFormatException` 异常,并输出了该异常的错误信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)