Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "throw new Exception" and "new Exception"?

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 ?

like image 252
Vineet Setia Avatar asked Oct 23 '16 07:10

Vineet Setia


2 Answers

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

like image 115
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 19 '22 11:10

ΦXocę 웃 Пepeúpa ツ


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()
like image 2
Daniel Scott Avatar answered Oct 19 '22 13:10

Daniel Scott