Java方法重载(Method Overloading)是指,同一个类中可以有多个方法名相同,但参数列表不同的方法。参数列表的不同可以体现在参数的数量、类型或顺序上。当涉及到异常处理时,重载方法可以有不同的异常声明,也可以有相同的异常声明,但它们的异常处理逻辑可以不同。
重载方法中的异常处理,示例:
public class MethodOverloadingExceptionHandling {
// 方法1
public void parseNumber(String input) throws NumberFormatException {
System.out.println("Parsing number: " + input);
int number = Integer.parseInt(input); // 这里可能抛出NumberFormatException
System.out.println("Parsed number: " + number);
}
// 方法2
public void parseNumberWithCondition(String input, boolean shouldThrow) throws MyCustomException, NumberFormatException {
System.out.println("Parsing number with condition: " + input + ", shouldThrow: " + shouldThrow);
try {
int number = Integer.parseInt(input); // 这里可能抛出NumberFormatException
if (shouldThrow) {
throw new MyCustomException("Custom exception thrown based on condition.");
}
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
// 这里可以处理NumberFormatException
System.err.println("Caught NumberFormatException: " + e.getMessage());
throw e; // 重新抛出NumberFormatException
}
}
// 自定义异常类
static class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
public static void main(String[] args) {
MethodOverloadingExceptionHandling example = new MethodOverloadingExceptionHandling();
try {
example.parseNumber("123"); // 调用方法1,正常解析数字
} catch (NumberFormatException e) {
System.err.println("Error in parseNumber: " + e.getMessage());
}
try {
example.parseNumberWithCondition("456", false); // 调用方法2,不抛出自定义异常
} catch (NumberFormatException | MyCustomException e) {
System.err.println("Error in parseNumberWithCondition: " + e.getMessage());
}
try {
example.parseNumberWithCondition("abc", true); // 调用方法2,将抛出自定义异常
} catch (NumberFormatException | MyCustomException e) {
System.err.println("Error in parseNumberWithCondition: " + e.getMessage());
}
}
}