Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is invocation of exception.fillInStacktrace useful?

I found an explicit invocation of e.fillInStacktrace() directly after creation of the exception Exception e = new Exception().

I think this is redundant, because the constructor of Throwable already invoke fillInStacktrace().

But maybe I overlooked something and this lines are useful:

Exception e = new Exception();
e.fillInStackTrace();
creationInfo = new CreationInfo(e.getStackTrace());

(public CreationInfo(StackTraceElement[] aStackTrace){...})

I think

  1. the additional invocation of e.fillInStackTrace(); directly after creation an exception is redundant and will wast a lot of resource, because this method is expensive.

  2. It seams that this construct is only needed to obtain the current stacktrace, therefore:

    creationInfo = Thread.currentThread().getStackTrace();
    

    is the better way.

Before filling an issue report I want to ask you if I have overlooked something?

like image 976
Ralph Avatar asked Mar 18 '13 08:03

Ralph


People also ask

Is it good to use printStackTrace?

The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.

What do you understand about Throwables in Java?

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.

What are Throwables?

A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Finally, it can contain a cause : another throwable that caused this throwable to get thrown.

What is the unwinding of the sequence of method calls typically referred to as?

This process is called stack unwinding. Unwinding the method-call stack means that the method in which the exception was not caught terminates, all local variables in that method are destroyed and control returns to the statement that originally invoked that method.


1 Answers

You are correct on both counts: the biggest reason why fillInStackTrace is even available is to let you override it in your own exceptions where you'd like to save the costs of providing the stack trace information, or where you need to hide the information about the location from which the exception may have been thrown. See this answer for more details.

like image 120
Sergey Kalinichenko Avatar answered Oct 19 '22 23:10

Sergey Kalinichenko