throws关键字用于在方法签名中声明该方法可能会抛出的异常,强制调用者显式处理异常。throw关键字用于抛出一个异常对象,中断程序的正常流程。
下面是使用throw
和throws
关键字的Java代码示例,以说明它们的用途:
使用throw
关键字抛出异常
public class ThrowExample {
public static void main(String[] args) {
try {
checkAge(-1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
public static void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
System.out.println("Age is valid.");
}
}
在这个例子中,checkAge
方法检查传入的年龄是否为负数。如果是,它使用throw
关键字抛出一个IllegalArgumentException
。main
方法中的try-catch
块捕获并处理这个异常。
使用throws
关键字声明异常
public class ThrowsExample {
public static void main(String[] args) {
try {
readFile("nonexistentfile.txt");
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
public static void readFile(String fileName) throws IOException {
if (fileName == null || fileName.isEmpty()) {
throw new IOException("File name cannot be null or empty.");
}
// 模拟文件读取操作
System.out.println("Reading file: " + fileName);
}
}
在这个例子中,readFile
方法可能会抛出IOException
,因此在方法签名中使用throws
关键字声明这个异常。main
方法必须处理这个异常,因为它是检查型异常。
同时使用throw
和throws
关键字
public class ThrowAndThrowsExample {
public static void main(String[] args) {
try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
e.printStackTrace();
}
}
public static int divide(int numerator, int denominator) throws ArithmeticException {
if (denominator == 0) {
throw new ArithmeticException("Denominator cannot be zero.");
}
return numerator / denominator;
}
}
在这个例子中,divide
方法检查分母是否为零。如果是,它使用throw
关键字抛出一个ArithmeticException
。由于这是一个检查型异常,divide
方法在其签名中使用throws
关键字声明这个异常。main
方法中的try-catch
块捕获并处理这个异常。
这些代码示例展示了如何在Java中使用throw
和throws
关键字来处理异常。throw
用于在代码中抛出异常,而throws
用于在方法签名中声明该方法可能会抛出的异常。
Comments NOTHING