Why do we need the throw keyword in Java?

In this answer, the code provided is:

void greet(String name) {

if (name == null) {

throw new IllegalArgumentException("Cannot greet null");

}

System.out.println("Hello, " + name);

}

I have seen similar examples on all sites where I went to learn the 'throw' keyword. What doesn't make sense to me whenever I see such examples is why would one simply not print: "Cannot greet null" instead of throwing an exception.

Questions:

1) Are there better examples of the utility of throw keyword? (I am just going to pass out of high school and know only high school...

Read More »

By: StackOverFlow - 5 days ago

Related Posts