Is it possible to create an exception without throwing it?

Suppose I have a class MyException that subclasses Exception. I use this class to include contextual information when errors occur in my code.

I usually use it to transfer one of the "standard" exception classes. For example, if an error occurs while checking the input, I will do something like

if (invalidInput())
  throw new MyException(new IllegalArgumentException(), arg1, arg2, ...);

But my IDE (Intellij IDEA) warns me that instantiating an exception to be thrown (IllegalArgumentException in this example) without throwing it is bad, but it doesn't tell me why.

So, how sinful is it to throw an exception without throwing it? What circle of hell am I going to?

+5
source share
5 answers

IllegalArgumentException, , :

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

IllegalArgumentException Exception, .

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

, .

Update: - , Throwable , : , , .

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

( a, b c - , ). , () , , , , / .

+8

, , . , , , .

, MyException RuntimeException;)

+2

.

, , , , -, . SO - ; , concurrency, .

IntelliJ , , , , , , , , , . , , . ( , , , "" IntelliJ).

+2

, .
invalidInput, IAE

    private void checkInput() throws IllegalArgumentException {
        if (...)
            throw new IllegalArgumentException();

:

    try {
        checkInput();
    } catch (IllegalArgumentException ex) {
        throw new MyException(ex, arg1, arg2, ...);
    }
+2

IntelliJ , . .

This check reports any instances of Throwable instantiation where the created Throwable never starts. Most often this is the result of a simple mistake.

+1
source

All Articles