0

I accidentally declared a method that throws an exception, (IllegalArgumentException), but I forgot to use throws.
I thought it's mandatory, and I wondered why the code compiled without any warning / error.
If it's not mandatory, then what is the purpose of it?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Lior
  • 5,841
  • 9
  • 32
  • 46

2 Answers2

1

You cannot throw a checked exception that isn't allowed by the throws clause. IllegalArgumentException, however, is a runtime exception, can you don't have to declare it.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • You _can_ throw checked exceptions without matching throws clauses. It is just not as simple and requires a helper function with a generic throws clause. – Jan Gassen Jan 29 '20 at 07:29
1

There are two (four) kinds of Throwables in Java.

  1. Plain Exceptions (and subclasses): You need to catch them or declare throws at the message signature
  2. RuntimeExceptions (and subclasses): As the name suggests, these happen because something fails at runtime (method call on null for example). These can be declared but don't have to (and some static code analysis tools complain if you do so). They can and should be caught somewhere.
  3. Errors (and subclasses): These happen is something out of scope of the current code goes wrong (OutOfMemoryError for example). These shouldn't be caught because you can't do anything with them...
  4. as @kaya stated Throwable itself: Should neither be thrown or caught.
Nicktar
  • 5,548
  • 1
  • 28
  • 43
  • What would be a better approach - always declaring methods with the `throws` keyword? – Lior Jan 29 '20 at 07:23
  • Technically, there is also `Throwable` itself, which isn't abstract, so you can `throw new Throwable();`. – kaya3 Jan 29 '20 at 07:25
  • @Lior That's opinon based and there are quite a few heated discussions about the use of checked and unchecked Exceptions in Java... Best to make up your own mind. – Nicktar Jan 29 '20 at 07:25