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?
Asked
Active
Viewed 79 times
0
-
3That's because it's a `java.lang.RuntimeException`. – Maroun Jan 29 '20 at 07:17
-
Can you please elaborate? – Lior Jan 29 '20 at 07:18
-
A method doesn't have to declare in its throws clause any subclasses of `RuntimeException`. – Maroun Jan 29 '20 at 07:19
2 Answers
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 Throwable
s in Java.
- Plain
Exception
s (and subclasses): You need to catch them or declare throws at the message signature RuntimeException
s (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.Error
s (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...- 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