在 Java 中,异常是程序在运行过程中发生的意外情况。Java 提供了强大的异常处理机制来应对这些情况,确保程序的健壮性和可维护性。
IOException
NullPointerException
ArrayIndexOutOfBoundsException
OutOfMemoryError
public class ExceptionHandlingExample { public static void main(String[] args) { try { int result = divide(10, 0); System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero: " + e.getMessage()); } finally { System.out.println("Execution completed."); } } public static int divide(int a, int b) throws ArithmeticException { return a / b; } }
正则表达式(Regular Expression)是一种字符串匹配模式,用于搜索、编辑和处理文本。Java 提供了 java.util.regex 包来支持正则表达式。
java.util.regex
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main(String[] args) { String text = "Hello, my email is example@example.com."; String regex = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); if (matcher.find()) { System.out.println("Found email: " + matcher.group()); } else { System.out.println("No email found."); } } }
Pattern.compile()
结合异常处理和正则表达式,以下是一个验证用户输入邮箱格式的示例:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class EmailValidator { private static final String EMAIL_REGEX = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b"; private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX); public static void main(String[] args) { String email = "user@example.com"; try { validateEmail(email); System.out.println("Email is valid."); } catch (InvalidEmailException e) { System.out.println("Invalid email: " + e.getMessage()); } } public static void validateEmail(String email) throws InvalidEmailException { Matcher matcher = EMAIL_PATTERN.matcher(email); if (!matcher.matches()) { throw new InvalidEmailException("Email format is incorrect."); } } } class InvalidEmailException extends Exception { public InvalidEmailException(String message) { super(message); } }
这个示例展示了如何使用正则表达式验证邮箱格式,并通过自定义异常类来处理无效输入。
原文链接:codingdict.net