Is Try-Catch More or Less Expensive Than Try-With-Resources

Related searches
Question

I've just started getting back into Java recently and never had an opportunity to use try-with-resources. On the surface it looks great as it can cut down on code, but under the hood is it more or less expensive of an operation than the traditional try-catch? I know try-catch already is an expensive operation, hence my curiosity.

I gave both types a simple test and didn't notice much of a difference at all:

Test Examples
Try-With-Resources Test
long startTime = System.currentTimeMillis();
ArrayList<String> list = null;

try (Scanner sc = new Scanner(new File("file.txt"))) {
    list = new ArrayList();
    while (sc.hasNext()) {
        list.add(sc.next());
    }
} catch (Exception ex) {
    System.err.println("Error: " + ex.getMessage());
} finally {
    long endTime = System.currentTimeMillis();
    System.out.println("The program completed in " + (endTime - startTime) + " ms");
}
Traditional Try-Catch Test
long startTime = System.currentTimeMillis();
ArrayList<String> list = null;
Scanner sc = null;

try {
    sc = new Scanner(new File("file.txt"));
    list = new ArrayList();
    while (sc.hasNext()) {
        list.add(sc.next());
    }
} catch (Exception ex) {
    System.err.println("Error: " + ex.getMessage());
} finally {
    sc.close();
    long endTime = System.currentTimeMillis();
    System.out.println("The program completed in " + (endTime - startTime) + " ms");
}
Results

Both resulted in a time of 15-16ms - no real noticeable difference at all. But admittedly this is a very small test example.

My question again: Under the hood is try-with-resources more or less expensive than a traditional try-catch?

  1. try-catch is not the expensive part. Throwing the exception is (generating the stacktrace).
  2. "Expensive" above means "costs some microseconds".
  3. try-with-resources is just try-catch with proper code needed to reliably close the resource.
  4. Your measurement code cannot prove anything due to all the well-known pitfalls of trying to measure performance within an optimizing runtime such as HotSpot. You need to warm up, repeat the same many times, and much more.
  5. If your result is above 10 ms, then clearly you cannot have an issue with try-catch, which can altogether impose an overhead of several microseconds.

Try With Resources vs Try-Catch, Seeing try {} finally {} isn't something that one often sees in Java code call in a try catch block costs less than 5% over a bare function call. And the login context has a Dispose method which will logout and clean up the resources. not expect this to be any more expensive or certainly not significantly� 21 Is Try-Catch More or Less Expensive Than Try-With-Resources; 10 Can I add a style tag to innerHTML? 9 Postback Fails On Default Document;

It's apples and oranges. An ARM (automatic resource management, or try-with-resources) block does more than the old-fashioned try-catch-finally block that you show. That's because it generates the code to handle exceptions that are thrown in resource closure with the suppression mechanism. (A related answer discusses this in some detail.)

If you are writing new code, use an ARM block. It is easier to read, maintain, and it does more. Unless you are running in a tightly constrained environment (like a smart card), these advantages are likely to outweigh the cost of a few extra byte codes.

Is try-finally expensive, In a previous article, we saw how to avoid nested try-catch-finally blocks in Java. In this article, we will have a look at how try-with-resources can avoid nested blocks The interface for AutoClosable has only one method as shown below: For more details on suppressed exceptions you can check out the Java docs here. 20 Is Try-Catch More or Less Expensive Than Try-With-Resources Jan 28 '15. 10 Can I add a style tag to innerHTML? Nov 12 '14. 9 Postback Fails On Default Document Dec

Try-catch-finally and try-with-resources have essentially the same performance because under the covers they generate essentially the same bytecode.

However, your second version (try..catch..finally) is not quite formulated correctly as it could (in theory) lead to an undesirable NullPointerException when sc.close() is called. If the act of constructing a Scanner causes an exception to be thrown then sc will not be assigned and will be null.

You should construct the Scanner outside of the try..finally and change this:

Scanner sc = null;
try {
    sc = new Scanner(new File("file.txt"));
    ...

to:

Scanner sc = new Scanner(new File("file.txt"));
try {
    ...

Alternatively, you should check that sc != null in the finally clause before calling sc.close(). This won't be necessary if you create the scanner outside of the try..finally, so I would recommend you do that.

To do the same job as try-with-resources, you will also need to put a second try..catch around the sc.close() with an empty catch block, to ignore any exceptions thrown during close. If you do that, I suppose you don't need to worry so much about the null check.

Exception Handling with Try with Resources Statement in Java 7 , This article presents the Java 7 answer to the automatic resource management Blockchain applications; Oracle vs AWS; Financials This requires disciplined usage of try/catch/finally blocks to ensure that any As we will see, it goes well beyond being just more syntactic sugar, like the enhanced for loops of Java SE 5. The result was very interesting. The cost of throwing and catching an exception seems to be rather low. In my sample it was about 0.002ms per Exception. This can more or less be neglected unless you really throw too many exceptions – and too many means we are talking about 100.000 or more.

Traditional Try-catch: In the try block, your code may have a exception, and this exception will be throw and then catch by the catch-block. Then the catch block will deal with the exception. And if you open a source, like a file or other things before a try, and you need to close them in finally then the close() executes in the finally may also throw a exception, and this will replace the exception which are throw in try This sitiution is solved by a nested try-catch before SE 7 like this

try
{
   try
  {
      code with exception;
  }
   finally
 {
      close();
 }

}
catch(Exception e)
{
  Deal the exception
}

this is really complex, so After SE 7 we use try-with-resource to solve this problem when you finish the try block, the resource in try(Here) will all be closed.

reference "Core Java" Edition:9 based on SE 7

Better Resource Management with Java SE 7, Generally finally block is used to close all the resources (viz., file, So a try-with- resources statement is nothing but a try statement that declares one or more resources. exception at all, it is better to use AutoCloseable for customization. Transient vs Static � Use of serialVersionUID � Java Thread Tutorial� The reason why Qt does not use exceptions is more or less historical. You have to know that the very first implementation was made over 12 years ago. At that time compilers supporting exceptions were not very common.

Exception Handling – The try-with-resources statement, Stack Exchange network consists of 177 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

more or less phrase. The red jacket is less expensive. (with a verb): Payments will be a lot less than many people were expecting.

Working in teams has resulted in distributing leadership throughout the district, so we need fewer people and get more positive results. Leadership personnel view their jobs as fluid and based on student needs instead of on a title and fixed position. —Merrianne Dyer, superintendent, Gainesville City Schools, Georgia. Using Less Expensive

Comments
  • Check the bytecode generated by using javap -c YourClassCompiled.class. If it's the same, then there's nothing to worry about.
  • docs.oracle.com/javase/specs/jls/se8/html/…
  • You can't measure millisecond-level delays with currentTimeMillis. The granularity is probably 15-16 ms, meaning it'll always report some multiple of that. Benchmarking is a complicated affair and the naive approach is seldom correct - see Nanotrusting nanotime.
  • The difference between the try-with-resources and your try-catch is that your try-catch is buggy. sc.close() may throw a NullPointerException. Even if the try-with-resources had a performance impact (which it doesn't), always use it. It will prevent bugs like these.
  • Interesting. It appears I have some reading to do. Thanks for the clear answer.
  • @Drew Take a look at jmh if you're interested in benchmarking Java code. I haven't used it yet, but it is designed for just this sort of thing.
  • Excellent point! Sloppily initializing to null like that is a bad habit too many programmers indulge in.
  • @erickson agreed. was more focused on the example than practices.
  • Yep, I was just being pedantic :-)