Difference between "throw new Exception" and "new Exception"?
Asked Answered
E

3

7

I am interested to know best practice to use throw new Exception() and new Exception(). In case of using new Exception(), I have seen that code moves to next statement instead of throwing exception.

But I am told that we should use new Exception() to throw RuntimeException.

Can anyone throw some light on this ?

Ex answered 23/10, 2016 at 7:38 Comment(2)
new Exception means create an instance (same as new Integer(...)) but no exception will happen until you throw it...Dorking
"I am told that we should use new Exception() to throw RuntimeException" by whom? where? with what reasoning? new Exception() does not throw the instantiated exception.Lavella
C
6

new Exception() means create an instance (same as creating new Integer(...)) but no exception will happen until you throw it...

Consider following snippet:

public static void main(String[] args) throws Exception {
    foo(1);
    foo2(1);
    }

    private static void foo2(final int number) throws Exception {
    Exception ex;
    if (number < 0) {
        ex = new Exception("No negative number please!");
        // throw ex; //nothing happens until you throw it
    }

    }

    private static void foo(final int number) throws Exception {
    if (number < 0) {
        throw new Exception("No negative number please!");
    }

    }

the method foo() will THROW an exception if the parameter is negative but the method foo2() will create an instance of exception if the parameter is negative

Confucius answered 23/10, 2016 at 7:44 Comment(0)
R
2
Exception e = new Exception ();

Just creates a new Exception, which you could later throw. Using

throw e;

Whereas

throw new Exception()

Creates and throws the exception in one line

To create and throw a runtime exception

throw new RuntimeException()
Remainderman answered 23/10, 2016 at 7:43 Comment(0)
P
1

new Exception() means you are creating a new instance of Exception type. Which means you are just instantiating an object similar to others like new String("abc"). You would do this when you are about to throw an exception of type Exception in next few lines of code execution.

While when you say throw new Exception() this means you are saying move the program control to caller and don't execute the further statements after this throw statement.

You would do this in a situation where you find that there is no way to move ahead and execute further and hence let caller know that i can't handle this case and if you know how to handle this case, please do so.

There is no best practice as such as you are comparing oranges with apples. But remember when throwing an exception, you always throw a meaningful exception like IO has where if file is not present it throws FileNotFoundException instead of its parent IOException.

Pu answered 23/10, 2016 at 7:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.