简体   繁体   中英

Comparing checked and unchecked exceptions (Performance, Benchmarks) in Java

Are there scenarios where you could argue that when an exception is created that both a checked exception and an unchecked exception can be used? Then the speed and performance can be measured against each other

From the perfomance point of view, building stack trace for exception is anyway the longest operation when an exception is generated ( details ).

Checked and unchecked exceptions make difference only at compile time. The Java compiler forces you to either catch checked exceptions or declare them in the method signature. It was supposed to improve program safety, but the majority opinion seems to be that it's not worth the design problems it creates.

There is even Lomboks "magical" @SneakyThrows annotation to overcome this compile-time check. On the JVM (class file) level, all exceptions, checked or not, can be thrown regardless of the throws clause of your methods, which is why this works.

As the others already said, there is no performance difference between checked and unchecked exceptions.

But if you think that the performance of throwing or handling exceptions might be important for your application, you're doing something terribly wrong .

Exceptions are meant to tell your caller that your method could not fulfill its task. If this happens so often that it affects your program's overall performance, you have a bigger problem than just the performance - you have a non-functional program!

Always throw exceptions when you find a method can't fulfill its task, and catch exceptions only in places where you can reasonably continue even after some unspecified failure of some method nested deeply in your call stack (that's what the exception tells you) - typically, that's some top level (like eg the menu bar action of a desktop app). To save you from writing lots of throws clases, unchecked exceptions can be helpful - but that's opinion-based.

Throwing an exception is very expensive because you need to calculate all of your stack traces, because of it often helps with performance just return null/-1/etc. Or you could use the constructor of Exception without writableStackTrace. it's the last parameters in the constructor. https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html

protected Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM