import java.util.regex.Pattern; public class UrlFormatException extends RuntimeException { private final String invalidUrl; public UrlFormatException(String message, String invalidUrl) { super(message); this.invalidUrl = invalidUrl; } public UrlFormatException(String message, String invalidUrl, Throwable cause) { super(message, cause); this.invalidUrl = invalidUrl; } public String getInvalidUrl() { return invalidUrl; } } class UrlValidator { private static final Pattern URL_PATTERN = Pattern.compile("^(https?|http)://[\\w-]+(\\.[\\w-]+)+([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?$"); public static void validate(String url) { if (url == null || url.isBlank()) { throw new UrlFormatException("URL不能为空", url); } if (!URL_PATTERN.matcher(url).matches()) { throw new UrlFormatException("URL格式不合法,仅支持http/https协议", url); } } public static void main(String[] args) { System.out.println("=== 测试 URL 校验 ==="); System.out.println("\n空URL校验:"); try { UrlValidator.validate(null); } catch (UrlFormatException e) { System.out.println(" 异常: " + e.getMessage()); System.out.println(" 无效URL: " + e.getInvalidUrl()); } System.out.println("\n非法URL校验:"); try { UrlValidator.validate("ftp://example.com"); } catch (UrlFormatException e) { System.out.println(" 异常: " + e.getMessage()); System.out.println(" 无效URL: " + e.getInvalidUrl()); } System.out.println("\n正确URL校验:"); try { UrlValidator.validate("https://www.example.com/page"); System.out.println(" 通过"); } catch (UrlFormatException e) { System.out.println(" 异常: " + e.getMessage()); } } }