在Java中,throw
和 throws
是与异常处理相关的两个关键字,它们用于不同的场景。
throw
:throw
关键字用于手动抛出一个异常对象。在方法内部,当发生某种异常情况时,可以使用 throw
将一个异常抛出。throw
后面通常紧跟着一个异常对象的创建或者已经存在的异常对象。
public class Example {
public static void main(String[] args) {
try {
throwException();
} catch (CustomException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
static void throwException() throws CustomException {
throw new CustomException("This is a custom exception.");
}
}
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
在上述示例中,throwException
方法使用 throw
抛出了一个自定义异常对象。
throws
:throws
关键字用于在方法签名中声明可能抛出的异常类型。当一个方法可能抛出某种异常,但该异常在方法内部不被捕获处理时,可以在方法声明上使用 throws
关键字列出可能抛出的异常类型。
public class Example {
public static void main(String[] args) {
try {
methodWithException();
} catch (CustomException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
static void methodWithException() throws CustomException {
throw new CustomException("This is a custom exception.");
}
}
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
在上述示例中,methodWithException
方法使用 throws
声明了可能抛出的异常类型。
throw
用于在方法内部手动抛出异常。throws
用于在方法声明中声明方法可能抛出的异常类型。在实际使用中,throw
通常用于抛出自定义异常或者已经存在的异常,而 throws
用于在方法签名中声明可能抛出的标准异常。