Is it ok to instantiate an exception without throwing it?

java

Solution

You might be better off throwing an instance of IllegalArgumentException, in this case that's what it's for:

if (invalidInput())
         new IllegalArgumentException("Invalid argument " + x + ", expected ...");

Or otherwise extending, IllegalArgumentException instead of Exception, it if you want to enhance it with custom properties.

public class MyIllegalArgumentException extends IllegalArgumentException {  
    public MyIllegalArgumentException(Object arg...) {    ....  } 
}

Both cases provide a leaner, more meaningful, class model.

Update: given your comment about wanting to supply contextual info with the thrown exception - you can do this by supplying your custom exception object as the Throwable argument to the standard exceptions contructor i.e. flip it round so: instead of wrapping the relevant standard exception in your exception, you should wrap your exception in the relevant standard exception.

if (invalidInput())
         new IllegalArgumentException("Invalid argument " + x + ", expected ...", new MyContextException(a,b,c));

(where a,b & c are the various bits of context you want to transmit). This way you (re)use a meaningful & appropriate, exception at all points in the code, but you transmit the contextual information that you may want to use further up the stack when handling/logging the exception.

Problem

Suppose I have a MyException class that subclasses Exception. I'm using this class to include contextual information when errors occur in my code. I typically use it to wrap one of the "standard" exception classes. For example, if an error happens during input validation, I will do something like ``` if (invalidInput()) throw new MyException(new IllegalArgumentException(), arg1, arg2, ...); ``` But my IDE (Intellij IDEA) warns me that instantiating an unchecked exception (IllegalArgumentException in this example) without throwing it is bad, but doesn't tell me why. So how sinful is it to instantiate an exception without throwing it? To which circle of hell will I go?

Original source