throws
throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)
语法:(修饰符)(方法名)([参数列表])[throws(异常类)]{…}
public void function() throws Exception{…}
当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理。
抛出,交给调用者处理
关于这句话的理解:方法存在预期会出现的问题,通过throws进行抛出异常的声明。但是方法本身不去处理这个问题,而是交给不同的调用人,调用这个方法的【能够预知到方法可能出现问题的调用者】进去捕捉处理
public static void function() throws NumberFormatException{
String s = "abc";
System.out.println(Double.parseDouble(s));
}
public static void main(String[] args) {
try {
function();
} catch (NumberFormatException e) {
System.err.println("非数据类型不能转换。");
//e.printStackTrace();
}
}
自定义异常 copy from chatgpt
public class Example {
public static void main(String[] args) {
try {
performOperation();
} catch (CustomException e) {
System.err.println("Caught an exception in the main method: " + e.getMessage());
// Handle the exception or perform additional actions
}
}
public static void performOperation() throws CustomException {
// Some condition that triggers an exception
if (/* some condition */) {
// Create an instance of CustomException and throw it
throw new CustomException("An error occurred during the operation");
}
}
}
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}