Why should we always throw new Exception? can we not store that exception as instance variable and throw the same instance everytime?

Arun Gowda :

In java, what I have seen so far is that whenever we throw an exception, we throw new Exception. Like the following example.

try{
    somethingThatCanGoWrong();
}catch(Exception e){
    throw new FailedToDoSomethingException("The other guy failed");
}

Is it always necessary to throw a new instance of an exception? Can I do it the following way?

public class Blah
{
    private static final FailedToDoSomethingException failedToDoSomethingException = new FailedToDoSomethingException(
        "The other guy failed" );

    public static void main( String[] args )
    {
        try {
            somethingThatCanGoWrong();
        } catch ( Exception e ) {
            throw failedToDoSomethingException;
        }
    }
}

I don't prefer the last example because of 2 reasons.

  1. Object orientally speaking, any Exception is neither a property of Class, nor the property of an instance.
  2. Fails miserably in multithreading environment when the Exception message is dynamically generated and is based on method argument. Following is the example.

    File getFile(String filePath){

    throw new FileNotFoundException("File at path: "+filePath+" was not found");

    }

Are there any more reasons apart from the above 2? Is there anything that goes on behind the scenes when we create the new instance of an exception? something like populating the exception Context(like stacktrace. But I believe that happens when we use the throw keyword)?

Or is it just a good practice to throw a new Exception all the time?(Again, WHY is it a good practice?)

Peter Lustig :

The stacktrace shows the line when the Exception was created, so you can't really see where it was thrown.

You can execute this example:

public class Foo {

    private static final RuntimeException re = new RuntimeException("MSG");

    public static void main(String[] args) {
        try {
            Integer.parseInt("!!#!");
        } catch (Exception e) {
            throw re;
        }
    }
}

When you take a look at the stacktrace:

Exception in thread "main" java.lang.RuntimeException: MSG
    at test.Foo.<clinit>(Foo.java:5)

You see that the line in the stacktrace is not the line where you actually throw the exception but rather the line were you call new

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=8061&siteId=1