Is It Expensive to Use Try-Catch Blocks Even If an Exception Is Never Thrown

Is it expensive to use try-catch blocks even if an exception is never thrown?

try has almost no expense at all. Instead of doing the work of setting up the try at runtime, the code's metadata is structured at compile time such that when an exception is thrown, it now does a relatively expensive operation of walking up the stack and seeing if any try blocks exist that would catch this exception. From a layman's perspective, try may as well be free. It's actually throwing the exception that costs you - but unless you're throwing hundreds or thousands of exceptions, you still won't notice the cost.


try has some minor costs associated with it. Java cannot do some optimizations on code in a try block that it would otherwise do. For example, Java will often re-arrange instructions in a method to make it run faster - but Java also needs to guarantee that if an exception is thrown, the method's execution is observed as though its statements, as written in the source code, executed in order up to some line.

Because in a try block an exception can be thrown (at any line in the try block! Some exceptions are thrown asynchronously, such as by calling stop on a Thread (which is deprecated), and even besides that OutOfMemoryError can happen almost anywhere) and yet it can be caught and code continue to execute afterwards in the same method, it is more difficult to reason about optimizations that can be made, so they are less likely to happen. (Someone would have to program the compiler to do them, reason about and guarantee correctness, etc. It'd be a big pain for something meant to be 'exceptional') But again, in practice you won't notice things like this.

What is the cost of try catch blocks?

Execution wise at run time, as long as there is no exception, try does not cost you anything. It only costs run time as soon as an exception occurs. And in that situation it is much slower that an if evaluation.

In the JVM spec, you see that there is no extra byte code generated on the execution path:
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12

In Javascript, is it expensive to use try-catch blocks even if an exception is never thrown?

Are you doing typical CRUD UI code? Use try catches, use loops that go to 10000 for no reason sprinkled in your code, hell, use angular/ember - you will not notice any performance issue.

If you are doing low level library, physics simulations, games, server-side etc then the never throwing try-catch block wouldn't normally matter at all but the problem is that V8 didn't support it in their optimizing compiler until version 6 of the engine, so the entire containing function that syntactically contains a try catch will not be optimized. You can easily work around this though, by creating a helper function like tryCatch:

function tryCatch(fun) {
try {
return fun();
}
catch(e) {
tryCatch.errorObj.e = e;
return tryCatch.errorObj;
}
}
tryCatch.errorObj = {e: null};

var result = tryCatch(someFunctionThatCouldThrow);
if(result === tryCatch.errorObj) {
//The function threw
var e = result.e;
}
else {
//result is the returned value
}

After V8 version 6 (shipped with Node 8.3 and latest Chrome), the performance of code inside try-catch is the same as that of normal code.

Do try/catch blocks hurt performance when exceptions are not thrown?

Check it.

static public void Main(string[] args)
{
Stopwatch w = new Stopwatch();
double d = 0;

w.Start();

for (int i = 0; i < 10000000; i++)
{
try
{
d = Math.Sin(1);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

w.Stop();
Console.WriteLine(w.Elapsed);
w.Reset();
w.Start();

for (int i = 0; i < 10000000; i++)
{
d = Math.Sin(1);
}

w.Stop();
Console.WriteLine(w.Elapsed);
}

Output:

00:00:00.4269033  // with try/catch
00:00:00.4260383 // without.

In milliseconds:

449
416

New code:

for (int j = 0; j < 10; j++)
{
Stopwatch w = new Stopwatch();
double d = 0;
w.Start();

for (int i = 0; i < 10000000; i++)
{
try
{
d = Math.Sin(d);
}

catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

finally
{
d = Math.Sin(d);
}
}

w.Stop();
Console.Write(" try/catch/finally: ");
Console.WriteLine(w.ElapsedMilliseconds);
w.Reset();
d = 0;
w.Start();

for (int i = 0; i < 10000000; i++)
{
d = Math.Sin(d);
d = Math.Sin(d);
}

w.Stop();
Console.Write("No try/catch/finally: ");
Console.WriteLine(w.ElapsedMilliseconds);
Console.WriteLine();
}

New results:

   try/catch/finally: 382
No try/catch/finally: 332

try/catch/finally: 375
No try/catch/finally: 332

try/catch/finally: 376
No try/catch/finally: 333

try/catch/finally: 375
No try/catch/finally: 330

try/catch/finally: 373
No try/catch/finally: 329

try/catch/finally: 373
No try/catch/finally: 330

try/catch/finally: 373
No try/catch/finally: 352

try/catch/finally: 374
No try/catch/finally: 331

try/catch/finally: 380
No try/catch/finally: 329

try/catch/finally: 374
No try/catch/finally: 334

Which part of throwing an Exception is expensive?

Creating an exception object is not necessarily more expensive than creating other regular objects. The main cost is hidden in native fillInStackTrace method which walks through the call stack and collects all required information to build a stack trace: classes, method names, line numbers etc.

Most of Throwable constructors implicitly call fillInStackTrace. This is where the idea that creating exceptions is slow comes from. However, there is one constructor to create a Throwable without a stack trace. It allows you to make throwables that are very fast to instantiate. Another way to create lightweight exceptions is to override fillInStackTrace.


Now what about throwing an exception?

In fact, it depends on where a thrown exception is caught.

If it is caught in the same method (or, more precisely, in the same context, since the context can include several methods due to inlining), then throw is as fast and simple as goto (of course, after JIT compilation).

However if a catch block is somewhere deeper in the stack, then JVM needs to unwind the stack frames, and this can take significantly longer. It takes even longer, if there are synchronized blocks or methods involved, because unwinding implies releasing of monitors owned by removed stack frames.


I could confirm the above statements by proper benchmarks, but fortunately I don't need to do this, since all the aspects are already perfectly covered in the post of HotSpot's performance engineer Alexey Shipilev: The Exceptional Performance of Lil' Exception.

Try..Catch blocks always expensive?

In general, in today's implementations, entering a try block is not expensive at all (this was not always true). However, throwing and handling an exception is usually a relatively expensive operation. So, exceptions should normally be used for exceptional events, not normal flow control.

Performance is only one factor to consider, though, especially in the modern world. If (for instance) you're doing something once in response to a user action, it probably doesn't matter from a performance standpoint whether you use an exception even when you could have done a proactive check instead, provided the exception happens quickly enough the user isn't jolted.¹ But if you're doing something in a tight loop that's going to run hundreds of thousands of times, or you're writing a web application that may need to handle a huge load, you'd probably want to avoid using an exception for a normal case.


¹ More than a decade ago I was responsible for enhancements to a .Net 1.1 "no touch deployment" application in which the first exception thrown took fully three seconds. This was a sufficient problem in one use case involving opening a file the user had asked for which might reasonably not be there that I had to add a check for file existence prior to trying to open the file, which is normally poor programming practice (just try to open the file and handle the exception if that fails), purely because the user experience waiting for that exception to get built was so poor. But that's probably not the world we live in now.

Why should I use nested try-catch blocks in Java?

OK - a bit contrived but demonstrates the point that the two try-catch structures are different - dependent on the actually implementation (this may be exactly what @KosztDojscia was pointing out so then consider this answer a duplicate) :

public class Main
{
public static class Exception1 extends Exception { }
public static class Exception2 extends Exception { }
public static class Exception3 extends Exception { }

public static void main(String[] args) {
int i = 0;

// "messy" structure
try {
try {
try {
i = 3; if (i == 3) throw new Exception1();
} catch (Exception1 e1) { i = 300; }

i = 4; if (i == 4) throw new Exception2();

} catch (Exception2 e2) { i = 400; }

i = 5; if (i == 5) throw new Exception3();

} catch (Exception3 e3) { i = 500; }

System.out.println(i);

// "clean" structure
try {
i = 3; if (i == 3) throw new Exception1();
i = 4; if (i == 4) throw new Exception2();
i = 5; if (i == 5) throw new Exception3();
} catch (Exception1 e1) { i = 300; }
catch (Exception2 e2) { i = 400; }
catch (Exception3 e3) { i = 500; }

System.out.println(i);

}
}

Prints:

500
300


Related Topics



Leave a reply



Submit