69.3k views
5 votes
What is the difference between the throw statement and the throws clause?

User Kyri Elia
by
6.4k points

1 Answer

4 votes

Answer:

throw and throws represent different constructs in Java programming language.

Step-by-step explanation:

throw is used to explicitly throw an Exception from within a code segment.

For example:

public void throw_test(String str){

if(str==null) throw new NullPointerException();

}

throws is used to specify an exception list which may be thrown by a method:

For example:

public String readFromFile(File f) throws IOException {

.....

// Some code fragment which could throw a IOException

}

User Niba
by
5.8k points