Câu hỏi phỏng vấn Java
Câu hỏi

What is the difference between throw and throws ?

Câu trả lời

In Java, throw and throws are both mechanisms used in exception handling, but they serve different purposes and are used in distinct contexts.

The throw Keyword

The throw keyword is used within a method or any block of code to explicitly throw an exception. This is typically done to indicate that an error or unusual situation has occurred, and the method cannot handle it or wishes to notify the calling method of the issue. The throw keyword is followed by an instance of Throwable (or one of its subclasses), which represents the specific exception to be thrown.

For example, if a method needs to indicate an error condition if a parameter value is incorrect, it might use throw to create and throw a new exception:

java Copy
public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}

In this example, throw is used to throw an IllegalArgumentException when an invalid age is passed to the method.

The throws Keyword

On the other hand, the throws keyword is used in the method signature to declare that a method might throw certain types of exceptions during its execution. This does not throw the exception itself but rather signals to the caller of the method that such exceptions might be thrown, and they should be prepared to handle them. Essentially, throws is used to indicate the potential exceptions that a method can propagate to its caller.

For instance, if a method performs file operations, it might declare that it throws IOException:

java Copy
public void readFile(String fileName) throws IOException {
    // Code that might throw IOException
}

Here, `throws IOExceptio...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

What is the basic principle of RMI architecture?

senior

What is meant by binding in RMI?

junior

What differences exist between HashMap and Hashtable ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào