Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Throwable.fillInStackTrace() method public? Why would someone use it?

Tags:

java

exception

I'm curious why is method fillInStackTrace of java.lang.Throwable public?

This method replaces original stack trace with that from the place it is called, removing the information needed to localize exception. It could be used for obfuscating, but without much effort, since new stack trace would direct to the obfuscation code. Better way would be to simply hide the exception or throw the new one.

But I can't find out any reasonable case for calling this method on existing Throwable. So the question is: why this method is public? Is there any sense behind?

like image 843
Danubian Sailor Avatar asked Mar 20 '12 14:03

Danubian Sailor


People also ask

What is the use of throwable 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 the useful methods of throwable classes in Java?

Java Throwable class provides several methods like addSuppressed(), fillInStackTrace(), getMessage(), getStackTrace(), getSuppressed(), toString(), printStackTrace() etc.

What does throwable do?

The throwable class implements Serializable Interface and the direct known classes to Throwable are Error and Exception. 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.

What is throwable cause in Java?

Throwable(Throwable cause) – Throwable has a single parameter, which specifies the actual cause of an Exception. Throwable(String desc, Throwable cause) – this constructor accepts an Exception description with the actual cause of an Exception as well.


1 Answers

One reason is for performance. Throwing and catching an exception is cheap; the expensive part is filling in the stack trace. If you override fillInStackTrace() to do nothing, creating an exception also becomes cheap.

With cheap exceptions, you can use exceptions for flow control, which can make the code more readable in certain situations; you can use them when when implementing JVM languages where you need more advanced flow control, and they are useful if you are writing an actors library.

like image 63
sbridges Avatar answered Oct 14 '22 05:10

sbridges