Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does throwing an exception change its state?

Tags:

java

exception

I've run some simple experiments like this:

public static void main(String[] args) {
    try {
        NullPointerException n = new NullPointerException();
        System.out.println(Lists.newArrayList(n.getStackTrace()));
        n.printStackTrace();
        System.out.println(Lists.newArrayList(n.getStackTrace()));
        throw n;
    } catch (NullPointerException e) {
        e.printStackTrace();
        System.out.println(Lists.newArrayList(e.getStackTrace()));
    }
}

and get output like this:

java.lang.NullPointerException
    at MyTest.main(MyTest.java:231)
java.lang.NullPointerException
    at MyTest.main(MyTest.java:231)
[MyTest.main(AbstractScannerTest.java:231)]
[MyTest.main(AbstractScannerTest.java:231)]
[MyTest.main(AbstractScannerTest.java:231)]

But I wonder if anything is done to an exception when it is thrown. This is a primarily academic question, though it could be relevant under certain circumstances if an exception were part of an API and may or may not have been thrown when provided to an implementation.

like image 591
Spina Avatar asked Oct 22 '22 04:10

Spina


1 Answers

No, the Throwable object itself is not modified by the throw operation; it is simply passed up the call stack similar to how a method's argument would be. Throwables are generally designed to be immutable objects and don't have setters, though some support modifying the stack trace so that RPC or similar frameworks can make sure that appropriate error-tracing information is included. That said, a Throwable is an object like any other, and you could write a Throwable class that had mutator methods to be called in a catch block, though that's not usual.

like image 117
chrylis -cautiouslyoptimistic- Avatar answered Oct 29 '22 00:10

chrylis -cautiouslyoptimistic-