Niklas R
Niklas R

Reputation: 16900

Why is it not necessary to catch the IllegalArgumentException?

I wonder why the IllegalArgumentException class does not need to be catched or declared, while other exceptions have to (eg java.net.MalformedURLException).

public void foo() {
    throw new IllegalArgumentException("spam");
}

public void bar() throws MalformedURLException { // required
    throw new MalformedURLException("ham");
}

I know that Errors do not have to be declared because they are not intended to be catched.

I'd like to declare a new exception which also does not require to be catched.

Upvotes: 7

Views: 2868

Answers (2)

zaerymoghaddam
zaerymoghaddam

Reputation: 3127

There are two types of Exceptions in Java: Checked Exceptions and Unchecked Exceptions. Checked exception has to be caught or declared to be thrown (like MalfomedURLException) but catching Unchecked exceptions (like IllegalArgumentException) is not mandatory and you can let the caller catch them (or throw them up to its own caller).

For more information, take a look at this post:

Java: Checked vs Unchecked Exceptions Explanation

If you extend your custom exception class from RuntimeException or any exception class inherited from it, then catching your exception will not be mandatory.

Upvotes: 8

Vijay
Vijay

Reputation: 1034

IllegalArgumentException is unchecked exception , so if you do not catch it then it will be handled by JVM , these exceptions are sublclasses of RuntimeException, Error, while MalformedURLException is checked exception which must be caught by programmer.All IOExceptions are checked exceptions Read here for more info

Upvotes: 1

Related Questions