when throwing an exception in java wh yd you need the keyword new


1 Answer

Monde Ngalonkulu
Monde Ngalonkulu
5,796 Points

Well, because you're throwing an error object instance - ie, an instance of an exception. And in Java you must use the new keyword to create an instance.

So maybe your question is sort of:

  1. why does Java use new when creating an object instance? Or
  2. why does Java use an instance to represent an exception?

  3. I won't go into 1 much, but it's just a language decision that was made for Java... probably because the English word provides intuition of what happens under the hood - a new instance of an object is created.

  4. Java uses an instance because an exception must have values related to the exception thrown - such as its message, cause and method stack. And given that Java is an object-oriented language, this makes sense.

You're probably comparing this with languages like Kotlin (or Python?) that don't use new when throwing an exception: throw IllegalArgumentException("Bad arg")

In the above example, kotlin doesn't use the new keyword. But that's because Kotlin doesn't use the new keyword when creating new instances. Again a language choice. But it is still creating an Exception instance initialized with the message "Bad arg"