How is the throw statement used in Java?
In Java, the keyword “throw” is used to raise exceptions. It is typically used in conjunction with try-catch statements to explicitly throw exceptions in the code.
The throw keyword can be used to manually throw an exception object, which can be a built-in exception class in Java or a custom exception class. The syntax is as follows:
throw 异常对象;
Below is an example demonstrating how to throw a custom exception class object using the throw keyword.
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
throw new MyException("This is a custom exception");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
In the above example, we defined a custom exception class called MyException, and threw a MyException object in the main method using the throw keyword. In the catch block, we caught the exception and printed out the message.
Please note that the throw keyword can only be used to throw exception objects, and cannot be used to throw primitive data types or null. Additionally, if the throw keyword is used to throw an exception in a method, the method declaration must use the throws keyword to declare the type of exception.