Search code examples
javaillegalargumentexception

About throwing IllegalArgumentException


I'm new to exceptions and this is what I know so far:

  • throws and throw are different

  • doing throw IllegalArgumentException I'll probably have to add throws IllegalArgumentException to the method signature

  • IllegalArgumentException is an unchecked exception and "Exceptions whose handling is not verified during Compile time"

Sources: http://javarevisited.blogspot.com/2011/12/checked-vs-unchecked-exception-in-java.html#ixzz2yM5jNFeg, http://www.tutorialspoint.com/java/java_exceptions.htm

This is a homework question: does throwing IllegalArgumentException make the program quit instantly?

The question seems a bit general and likely to be false, but I'm not entirely clear about IllegalArgumentException either. The sources did not really exemplify throw in a simple way, so I'm still confused. So, it would be great if there could be a simple explanation to this.


Solution

  • Throwing any exception makes the current method exit immediately, but not the whole program. Furthermore, the exception will continue being thrown at the calling method, from where the first method threw it; this is called propagation. Whether it keeps going at that point depends on whether that calling method catches the exception. If nothing catches the exception, it'll propagate all the way back to the main method (this is assuming a simple, single-threaded application), and if that method also throws it, then the program will exit.

    void callee() {
        if (someTrueCondition()) {
            throw new IllegalArgumentException("whatever");
        }
        System.out.println("this will never get called");
    }
    
    void caller() {
        calle(); // the IllegalArgumentException propagates from here
        System.out.println("this will also never get called");
    }
    

    The above is true for any exception. What makes IllegalArgumentException different from others is only the fact that it's unchecked, and thus doesn't need to be declared in a throws clause on the method that may throw it. (Note that in your question, you said you probably would need to declare throws IllegalArgumentException, but you actually don't, because it's an unchecked exception.)

    If you were instead throwing a checked exception (e.g., throw new SQLException()), then both callee and caller would need to declare that exception. callee would need to declare it because it throws that exception directly, and caller would need to declare it because it may throw that exception indirectly, via propagation from callee.

    The only way to stop this propagation (both of the exception at runtime, and of the throws clauses at compile-time) is to catch the given exception with a try-catch.