Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

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

yah

1 Answer

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"