The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

The try-with-resources Statement
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable , can be used as a resource.
The following example reads the first line from a file. It uses an instance of FileReader and BufferedReader to read data from the file. FileReader and BufferedReader are resources that must be closed after the program is finished with it:
In this example, the resources declared in the try -with-resources statement are a FileReader and a BufferedReader . The declaration statements of these resources appear within parentheses immediately after the try keyword. The classes FileReader and BufferedReader , in Java SE 7 and later, implement the interface java.lang.AutoCloseable . Because the FileReader and BufferedReader instances are declared in a try -with-resource statement, they will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException ).
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try -with-resources statement:
However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource's memory when it's finished with it. The program must also release the resoure back to the operating system, typically by calling the resource's close method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked.
In this example, if the readLine method throws an exception, and the statement br.close() in the finally block throws an exception, then the FileReader has leaked. Therefore, use a try -with-resources statement instead of a finally block to close your program's resources.
If the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile , if exceptions are thrown from both the try block and the try -with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try -with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.
The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
In this example, the try -with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter . When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.
The following example uses a try -with-resources statement to automatically close a java.sql.Statement object:
The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.
Note : A try -with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try -with-resources statement, any catch or finally block is run after the resources declared have been closed.
Suppressed Exceptions
An exception can be thrown from the block of code associated with the try -with-resources statement. In the example writeToFileZipFileContents , an exception can be thrown from the try block, and up to two exceptions can be thrown from the try -with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try -with-resources statement, then those exceptions thrown from the try -with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.
Classes That Implement the AutoCloseable or Closeable Interface
See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception . Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException , or no exception at all.
About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights
Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Final variable assignment with try/catch
Because I believe it is a good programming practice, I make all my (local or instance) variables final if they are intended to be written only once.
However, I notice that when a variable assignment can throw an exception you cannot make said variable final:
Is there a way to do this without resorting to a temporary variable? (or is this not the right place for a final modifier?)
- 1 I doubt you can do this without a temporary variable. – NPE Nov 28, 2012 at 11:35
- 11 final int x = makeX(); definitely. (try-catch in function) – Joop Eggen Nov 28, 2012 at 11:36
- 2 Shocking that the JDK still doesn't have a tryParse . – T.J. Crowder Nov 28, 2012 at 11:41
- 12 To be perfectly clear, the compiler error is incorrect, is it not? There is no circumstance under which x could be assigned twice in the given example. – jaco0646 Oct 22, 2014 at 19:41
- 4 @jaco0646, it's asking a lot for the compiler to get that in general when there are multiple lines in the try block where the exception might happen. It would be nice to have an exceptional case for this purpose, though, detecting when the assignment is the last statement in the try. – Joshua Goldberg Jun 10, 2016 at 17:26
2 Answers 2
One way to do this is by introducing a (non- final ) temporary variable, but you said you didn't want to do that.
Another way is to move both branches of the code into a function:
Whether or not this is practical depends on the exact use case.
All in all, as long as x is a an appropriately-scoped local variable, the most practical general approach might be to leave it non- final .
If, on the other hand, x is a member variable, my advice would be to use a non- final temporary during initialization:
- For a local scope I agree with you, however this most often occurs with instance variables. – dtech Nov 28, 2012 at 11:45
- I guess it could reflect an error cannot make a static reference to the non-static method getValue(), so we are suppose to use the static function ,, i may be wrong private static int getValue() [email protected] – thar45 Nov 28, 2012 at 11:45
- 1 If this.x is an object-type like Integer, then you need a little more (sadly). If you leave x_val undeclared, the compiler will complain that it may not have been initialized. If the fall-back for the catch block is null, you need to pre-initialize to null and either redundantly assign null in the catch for clarity (that's my preference) or have an empty catch. – Joshua Goldberg Jun 10, 2016 at 17:37
- What @JoshuaGoldberg says is true even for primitive types. We have exactly the same pattern of code, where the member in the role of this.x is a primitive boolean , as is the local variable. Even with Java 9, we get "<thing_in_the_role_of_ x_val > may not have been initialized". The lack of control-flow analysis for this situation is frustrating, but easily worked around. – Ti Strga Nov 15, 2018 at 17:03
No it is not the right place, imagine you got more then 1 Statement in your try and catch block, the first one says : x = 42. After some others Statements the try block fails, and it goes to the catch block, where your Saying x = 30. Now you defined x twice.
- 17 The compiler is smart enough to know which statements throw which exceptions. It may not be possible in all cases but just like the compiler can tell you in some cases about dead code etc. it should be able to figure out if final would work. – Stefan Feb 18, 2014 at 17:43
- To support what @Stefan said, Clang is able to figure this out when compiling Swift. – Franklin Yu Apr 29, 2016 at 2:25
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged java final or ask your own question .
- The Overflow Blog
- Building an API is half the battle: Q&A with Marco Palladino from Kong
- Developers think AI assistants will be everywhere, but aren’t sure how to...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The Stack Exchange reputation system: What's working? What's not?
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Are there 2 Parkruns close enough together with a large enough start time difference such that one could run both on one day?
- What is this || notation in BIP 341?
- Why is \textsc not working on this tabularray?
- Walsh-Hadamard transform in randomness testing
- In what sense the laser radiation is monochromatic?
- Best way to highlight the main result in a mathematical paper
- Why isn't the taproot deployment buried in Bitcoin Core?
- Why isn't the derivative of the volume of the cone its surface area?
- Why does potassium bifluoride exist whereas bichloride does not?
- Is post-hyphenation necessary in "I am a child and adult psychologist..."?
- Is it possible to have seasonality at 24, 12, 8 periods in hourly based wind power data?
- What does 'encore' mean in this sentence?
- Theoretical Computer Science vs other Sciences?
- Was Freemasonry such a big problem in 1980s UK policing?
- Why is the ongoing auction for Silicon Valley Bank started privately held (vs. publicly)?
- How were rackmount workstations wired-up to mice, keyboards, monitors, etc?
- Under what circumstance is it a crime if a car owner allows someone other than themself to drive their car?
- I need to have each line of a file run in a subshell of its own
- I arrive 30 minutes before my visa start date. Would I be allowed to board the plane in my home airport?
- What is the concept of hole in semiconductor physics?
- A melody is built from both notes and chords
- Would it be possible for a planet to orbit around a trinary star system in a figure 8 orbit?
- Is there an objective standard for power measurement?
- Short fantasy about disappearing items - Asimov's early 1980s
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Welcome to Java
Using try/catch blocks assignment.
- Java Exception Handling
- Basic try-catch-finally Exception Handling in Java
Java Try With Resources
- Catching Multiple Exceptions in Java 7
- Exception Hierarchies
- Checked or Unchecked Exceptions?
- Exception Wrapping
- Fail Safe Exception Handling
- Pluggable Exception Handlers
- Logging Exceptions: Where to Log Exceptions?
- Validation - Throw Exceptions Early
- Validation - Throw Exception or Return False?
- Exception Handling Templates in Java
- Exception Enrichment in Java
- Execution Context
Try-with-resources Video
Try-with-resources, try-with-resources java 9 enhancement, closing order, custom autoclosable implementations, catch block, finally block, adding suppressed exceptions manually, resource management with try-catch-finally, old school style.
The Java try with resources construct, AKA Java try-with-resources , is an exception handling mechanism that can automatically close resources like a Java InputStream or a JDBC Connection when you are done with them. To do so, you must open and use the resource within a Java try-with-resources block. When the execution leaves the try-with-resources block, any resource opened within the try-with-resources block is automatically closed, regardless of whether any exceptions are thrown either from inside the try-with-resources block, or when attempting to close the resources.
This Java try-with-resources tutorial explains how the Java try-with-resources construct works, how to properly use it, and how exceptions are handled that are thrown both from inside the try-with-resources block, and during the closing of the resources.
I have created a video version of this Java try-with-resources tutorial, in case you prefer that:
To see how the Java try-with-resources construct work, let us look at a Java try-with-resources example:
This try-with-resources example shows how to open a Java FileInputStream inside a try-with-resources block, read some data from the FileInputStream , and have the FileInputStream closed automatically once execution leaves the try-with-resources block (not explicitly visible).
Notice the first line inside the method in the try-with-resources example above:
This is the try-with-resources construct. The FileInputStream variable is declared inside the parentheses after the try keyword. Additionally, a FileInputStream is instantiated and assigned to the variable.
When the try block finishes the FileInputStream will be closed automatically. This is possible because FileInputStream implements the Java interface java.lang.AutoCloseable . All classes implementing this interface can be used inside the try-with-resources construct.
Before Java 9 a resource that is to be automatically closed must be created inside the parentheses of the try block of a try-with-resources construct. From Java 9, this is no longer necessary. If the variable referencing the resource is effectively final, you can simply enter a reference to the variable inside the try block parentheses. Here is an example of the Java 9 try-with-resources enhancement:
Notice how the input variable is now declared and has a FileInputStream assigned outside the try block. Notice also, how the input variable is references inside the parentheses of the try block. This way, Java will still close it properly once the try block is exited.
Using Multiple Resources
You can use multiple resources inside a Java try-with-resources block and have them all automatically closed. Here is an example of using multiple resources inside a try-with-resources block:
This example creates two resources inside the parentheses after the try keyword. An FileInputStream and a BufferedInputStream . Both of these resources will be closed automatically when execution leaves the try block.
The resources declared in a Java try-with-resources construct will be closed in reverse order of the order in which they are created / listed inside the parentheses. In the example in the previous section, first the will be closed, then the FileInputStream .
The Java try-with-resources construct does not just work with Java's built-in classes. You can also implement the java.lang.AutoCloseable interface in your own classes, and use them with the try-with-resources construct.
The AutoClosable interface only has a single method called close() . Here is how the interface looks:
Any class that implements this interface can be used with the Java try-with-resources construct. Here is a simple example implementation:
The doIt() method is not part of the AutoClosable interface. It is there because we want to be able to do something more than just closing the object.
Here is an example of how the MyAutoClosable is used with the try-with-resources construct:
Here is the output printed to System.out when the method myAutoClosable() is called:
As you can see, try-with-resources is a quite powerful way of making sure that resources used inside a try-catch block are closed correctly, no matter if these resources are your own creation, or Java's built-in components.
Try-with-resources Exception Handling
The exception handling semantics of a Java try-with-resources block vary a bit from the exception handling semantics of a standard Java try-catch-finally block. In most situations the changed semantics will work better for you than the semantics of the original try-catch-finally block, even without you understanding the difference precisely. Even so, it can be a good idea to actually understand what is going on exception handling wise, in the try-with-resources construct. Therefore I will explain the exception handling semantics of the try-with-resources construct here.
If an exception is thrown from within a Java try-with-resources block, any resource opened inside the parentheses of the try block will still get closed automatically. The throwing of the exception will force the execution to leave the try block, and this will force the automatic closing of the resource. The exception thrown from inside the try block will get propagated up the call stack, once the resources have been closed.
Some resources may also throw exceptions when you try to close them. In case a resource throws an exception when you try to close it, any other resources opened within the same try-with-resources block will still get closed. After closing all resources, the exception from the failed close-attempt will get propagated up the call stack. In case multiple exceptions are thrown from multiple resource close attempts, the first exception encountered will be the one propagated up the call stack. The rest of the exceptions will be suppressed.
If an exception is thrown both from inside the try-with-resources block, and when a resource is closed (when close() is called), the exception thrown inside the try block will be propagated up the call stack. The exception thrown when the resource was attempted closed will be suppressed. This is opposite of what happens in a normal try-catch-finally block, where the last exception encountered is the exception that is propagated up the call stack.
To better understand the exception handling semantics of the Java try-with-resources construct, let us look at some examples. For these examples I have created the following AutoClosable implementation which I can force to throw exceptions both when used and when attempted closed:
First, let us look at a basic example with a single resource in use:
In case the second parameter to the AutoClosableResource construct was changed to true , it would throw an exception when attempted closed. In that case, the exception thrown when attempted closed will be propagated up the call stack to the main() method where the try-catch block will catch it. In that case, the Throwable array returned from e.getSuppessed() will be an empty array (size of 0).
In case the parameter to resourceOne.doOp() was changed to true also, the doOp() method would throw an exception. In that case, it is this exception that is propagated up the call stack to the main() method. The exception thrown when attempting to close the resource would be available inside the Throwable array returned by e.getSuppressed() .
Let us look at an example with two AutoClosable resources in use:
In the case where only one of the resources throw an exception, either during use or when attempted closed, the behaviour is the same as when only one resource is used. However, in the example above I have forced both resources to throw an exception when attempted closed, and the first resource to throw an exception when used (when doOp() is called). In that case, the exception thrown from inside the try block is propagated up the call stack. The two exceptions thrown when attempting to close the resources are available in the Throwable array returned by e.getSuppressed() .
Remember, only a single exception can be thrown inside the try block. As soon as an exception is thrown, the try block code is exited, and the resources attempted closed.
You can add a catch block to a try-with-resources block just like you can to a standard try block. If an exception is thrown from within the try block of a try-with-resources block, the catch block will catch it, just like it would when used with a standard try construct.
Before the catch block is entered, the try-with-resources construct will attempt to close the resources opened inside the try block. In case an exception is thrown when attempting to close one of the resources, these exceptions will be available from the exception's getSuppressed() method inside the catch block. Here is an example of a Java try-with-resources block with a catch block attached:
In the example above, the AutoClosableResource is configured to throw an exception both when doOp() is called, and when it is attempted closed (via close() ). The exception thrown from doOp() is caught in the catch block, its getSuppressed() method returns an array with the exception thrown when the resource was attempted closed.
In case that an exception is only thrown when the resource is attempted closed, the catch block will also catch it. The getSuppressed() method of that exception will return an empty array, since no exceptions where suppressed.
It is also possible to add a finally block to a Java try-with-resources block. It will behave just like a standard finally block, meaning it will get executed as the last step before exiting the try-with-resources block - after any catch block has been executed.
In case you throw an exception from within the finally block of a try-with-resources construct, all previously thrown exceptions will be lost! Here is an example of throwing an exception from within the finally block of a Java try-with-resources construct:
Notice, that the exception thrown from within the catch block will be ignored because a new exception is thrown from within the finally block. This would also be true if there was no catch block. Then any exception thrown from inside the try block would get lost because a new exception is thrown from inside the finally block. Any previous exceptions are not suppressed, so they are not available from within the exception thrown from the finally block.
The Throwable class has a method named addSuppressed() which takes a Throwable object as parameter. Using the addSuppressed() method it is possible to add suppressed exceptions to another exception, in case you need that. Here is an example that shows how to add suppressed exceptions to a Java exception manually:
Notice how the Throwable reference has to be declared outside the try-with-resources construct. Otherwise the catch and finally blocks cannot access it.
In most cases you will not need to add suppressed exceptions to an exception manually, but now you have at least seen how it can be done, in case you ever run into a situation where you need it.
The Java try-with-resources construct was added in Java 7. Managing resources that need to be explicitly closed was somewhat tedious before Java 7. You had to handle the correct closure of the resources manually. This was not an easy task to handle correctly. To understand why, look at the following method which reads a file and prints it to the System.out :
The code marked in bold is where the code can throw an Exception . As you can see, that can happen in 3 places inside the try -block, and 1 place inside the finally -block.
The finally block is always executed no matter if an exception is thrown from the try block or not. That means, that the InputStream is closed no matter what happens in the try block. Or, attempted closed that is. The InputStream 's close() method may throw an exception too, if closing it fails.
Imagine that an exception is thrown from inside the try block. Then the finally block is executed. Imagine then, that an exception is also thrown from the finally block. Which exception do you think is propagated up the call stack?
The exception thrown from the finally block would be propagated up the call stack, even if the exception thrown from the try block would probably be more relevant to propagate.

- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
- Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Arrays in Java
- Spring Boot - Start/Stop a Kafka Listener Dynamically
- Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
- Split() String method in Java with examples
- Arrays.sort() in Java with examples
- For-each loop in Java
- Reverse a string in Java
- Object Oriented Programming (OOPs) Concept in Java
- How to iterate any Map in Java
- HashMap in Java with Examples
- Initialize an ArrayList in Java
- Multidimensional Arrays in Java
- ArrayList in Java
- Stack Class in Java
- How to add an element to an Array in Java?
- Interfaces in Java
- Overriding in Java
- Set in Java
- LinkedList in Java
- Java Singleton Class
- Inheritance in Java
- Collections in Java
- Queue Interface In Java
- Classes and Objects in Java
- Convert a String to Character Array in Java
- Collections.sort() in Java with Examples
- Initializing a List in Java
- Multithreading in Java
- Math pow() method in Java with Example
- Polymorphism in Java
Try-with-resources Feature in Java
- Difficulty Level : Medium
- Last Updated : 30 Nov, 2022
In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. For example, a File resource or a Socket connection resource. The try-with-resources statement ensures that each resource is closed at the end of the statement execution. If we don’t close the resources, it may constitute a resource leak and also the program could exhaust the resources available to it.
You can pass any object as a resource that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable.
By this, now we don’t need to add an extra finally block for just passing the closing statements of the resources. The resources will be closed as soon as the try-catch block is executed.
Syntax: Try-with-resources
Exceptions:
When it comes to exceptions, there is a difference in try-catch-finally block and try-with-resources block. If an exception is thrown in both try block and finally block, the method returns the exception thrown in finally block.
For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.
Now, let us discuss both the possible scenarios which are demonstrated below as an example as follows:
- Case 1 : Single resource
- Case 2: Multiple resources
Example 1: try-with-resources having a single resource
Output:
Example 2: try-with-resources having multiple resources
Output:
Please Login to comment...
- surinderdawra388
- Java-Exception Handling
Master Java Programming - Complete Beginner to Advanced
Java backend development - live, master c programming with data structures, data structures and algorithms - self paced, competitive programming - live, full stack development with react & node js - live, complete interview preparation - self paced, python backend development with django - live, complete test series for service-based companies, system design - live, improve your coding skills with practice, start your coding journey now.
Learn Java interactively.
Learn Java practically and Get Certified .
Popular Tutorials
Popular examples, reference materials.
Learn Java Interactively
Java Introduction
- Java Hello World
- Java JVM, JRE and JDK
- Java Variables and Literals
- Java Data Types
- Java Operators
- Java Input and Output
- Java Expressions & Blocks
- Java Comment

Java Flow Control
- Java if...else
- Java switch Statement
- Java for Loop
- Java for-each Loop
- Java while Loop
- Java break Statement
- Java continue Statement
- Java Arrays
- Multidimensional Array
- Java Copy Array
Java OOP (I)
- Java Class and Objects
- Java Methods
- Java Method Overloading
- Java Constructor
- Java Strings
- Java Access Modifiers
- Java this keyword
- Java final keyword
- Java Recursion
- Java instanceof Operator
Java OOP (II)
- Java Inheritance
- Java Method Overriding
- Java super Keyword
- Abstract Class & Method
- Java Interfaces
- Java Polymorphism
- Java Encapsulation
Java OOP (III)
- Nested & Inner Class
- Java Static Class
- Java Anonymous Class
- Java Singleton
- Java enum Class
- Java enum Constructor
- Java enum String
- Java Reflection
Java Exception Handling
- Java Exceptions
- Java try...catch
Java throw and throws
Java catch Multiple Exceptions
Java try-with-resources
- Java Annotations
- Java Annotation Types
- Java Logging
- Java Assertions
- Java Collections Framework
- Java Collection Interface
- Java List Interface
- Java ArrayList
- Java Vector
- Java Queue Interface
- Java PriorityQueue
- Java Deque Interface
- Java LinkedList
- Java ArrayDeque
- Java BlockingQueue Interface
- Java ArrayBlockingQueue
- Java LinkedBlockingQueue
- Java Map Interface
- Java HashMap
- Java LinkedHashMap
- Java WeakHashMap
- Java EnumMap
- Java SortedMap Interface
- Java NavigableMap Interface
- Java TreeMap
- Java ConcurrentMap Interface
- Java ConcurrentHashMap
- Java Set Interface
- Java HashSet
- Java EnumSet
- Java LinkedhashSet
- Java SortedSet Interface
- Java NavigableSet Interface
- Java TreeSet
- Java Algorithms
- Java Iterator
- Java ListIterator
- Java I/O Streams
- Java InputStream
- Java OutputStream
- Java FileInputStream
- Java FileOutputStream
- Java ByteArrayInputStream
- Java ByteArrayOutputStream
- Java ObjectInputStream
- Java ObjectOutputStream
- Java BufferedInputStream
- Java BufferedOutputStream
- Java PrintStream
Java Reader/Writer
- Java Reader
- Java Writer
- Java InputStreamReader
- Java OutputStreamWriter
- Java FileReader
- Java FileWriter
- Java BufferedReader
- Java BufferedWriter
- Java StringReader
- Java StringWriter
- Java PrintWriter
Additional Topics
- Java Scanner Class
- Java Type Casting
- Java autoboxing and unboxing
- Java Lambda Expression
- Java Generics
- Java File Class
- Java Wrapper Class
- Java Command Line Arguments
Related Topics
- Java PrintWriter Class
In this tutorial, we will learn about the try catch statement in Java with the help of examples.
The try...catch block in Java is used to handle exceptions and prevents the abnormal termination of the program.
Here's the syntax of a try...catch block in Java.
The try block includes the code that might generate an exception.
The catch block includes the code that is executed when there occurs an exception inside the try block.
Example: Java try...catch block
In the above example, notice the line,
Here, we are trying to divide a number by zero . In this case, an exception occurs. Hence, we have enclosed this code inside the try block.
When the program encounters this code, ArithmeticException occurs. And, the exception is caught by the catch block and executes the code inside the catch block.
The catch block is only executed if there exists an exception inside the try block.
Note : In Java, we can use a try block without a catch block. However, we cannot use a catch block without a try block.
Java try...finally block
We can also use the try block along with a finally block.
In this case, the finally block is always executed whether there is an exception inside the try block or not.
Example: Java try...finally block
In the above example, we have used the try block along with the finally block. We can see that the code inside the try block is causing an exception.
However, the code inside the finally block is executed irrespective of the exception.
Java try...catch...finally block
In Java, we can also use the finally block after the try...catch block. For example,
In the above example, we have created an array named list and a file named output.txt . Here, we are trying to read data from the array and storing to the file.
Notice the code,
Here, the size of the array is 5 and the last element of the array is at list[4] . However, we are trying to access elements at a[5] and a[6] .
Hence, the code generates an exception that is caught by the catch block.
Since the finally block is always executed, we have included code to close the PrintWriter inside the finally block.
It is a good practice to use finally block to include important cleanup code like closing a file or connection.
Note : There are some cases when a finally block does not execute:
- Use of System.exit() method
- An exception occurs in the finally block
- The death of a thread
- Multiple Catch blocks
For each try block, there can be zero or more catch blocks. Multiple catch blocks allow us to handle each exception differently.
The argument type of each catch block indicates the type of exception that can be handled by it. For example,
In this example, we have created an integer array named arr of size 10 .
Since the array index starts from 0 , the last element of the array is at arr[9] . Notice the statement,
Here, we are trying to assign a value to the index 10 . Hence, IndexOutOfBoundException occurs.
When an exception occurs in the try block,
- The exception is thrown to the first catch block. The first catch block does not handle an IndexOutOfBoundsException , so it is passed to the next catch block.
- The second catch block in the above example is the appropriate exception handler because it handles an IndexOutOfBoundsException . Hence, it is executed.
- Catching Multiple Exceptions
From Java SE 7 and later, we can now catch more than one type of exception with one catch block.
This reduces code duplication and increases code simplicity and efficiency.
Each exception type that can be handled by the catch block is separated using a vertical bar | .
Its syntax is:
To learn more, visit Java catching multiple exceptions .
- Java try-with-resources statement
The try-with-resources statement is a try statement that has one or more resource declarations.
The resource is an object to be closed at the end of the program. It must be declared and initialized in the try statement.
Let's take an example.
The try-with-resources statement is also referred to as automatic resource management . This statement automatically closes all the resources at the end of the statement.
To learn more, visit the java try-with-resources statement .
Table of Contents
- Example: try...catch block
- Java try...finally
- Java try...catch...finally
Sorry about that.
Related Tutorials
Java Tutorial
Try PRO for FREE

- Runestone in social media: Follow @iRunestone Our Facebook Page
- Table of Contents
- Assignments
- Peer Instruction (Instructor)
- Peer Instruction (Student)
- Change Course
- Instructor's Page
- Progress Page
- Edit Profile
- Change Password
- Scratch ActiveCode
- Scratch Activecode
- Instructors Guide
- About Runestone
- Report A Problem
- 1.1 Preface
- 1.2 Why Programming? Why Java?
- 1.3 Variables and Data Types
- 1.4 Expressions and Assignment Statements
- 1.5 Compound Assignment Operators
- 1.6 Casting and Ranges of Variables
- 1.7 Java Development Environments (optional)
- 1.8 Unit 1 Summary
- 1.9 Unit 1 Mixed Up Code Practice
- 1.10 Unit 1 Coding Practice
- 1.11 Multiple Choice Exercises
- 1.12 Lesson Workspace
- 1.3. Variables and Data Types" data-toggle="tooltip">
- 1.5. Compound Assignment Operators' data-toggle="tooltip" >
1.4. Expressions and Assignment Statements ¶
In this lesson, you will learn about assignment statements and expressions that contain math operators and variables.
1.4.1. Assignment Statements ¶
Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator = . An assignment statement always has a single variable on the left hand side of the = sign. The value of the expression on the right hand side of the = sign (which can contain math operators and other variables) is copied into the memory location of the variable on the left hand side.

Figure 1: Assignment Statement (variable = expression) ¶
Instead of saying equals for the = operator in an assignment statement, say “gets” or “is assigned” to remember that the variable on the left hand side gets or is assigned the value on the right. In the figure above, score is assigned the value of 10 times points (which is another variable) plus 5.
The following video by Dr. Colleen Lewis shows how variables can change values in memory using assignment statements.
As we saw in the video, we can set one variable to a copy of the value of another variable like y = x;. This won’t change the value of the variable that you are copying from.

Click on the Show CodeLens button to step through the code and see how the values of the variables change.
The program is supposed to figure out the total money value given the number of dimes, quarters and nickels. There is an error in the calculation of the total. Fix the error to compute the correct amount.
Calculate and print the total pay given the weekly salary and the number of weeks worked. Use string concatenation with the totalPay variable to produce the output Total Pay = $3000 . Don’t hardcode the number 3000 in your print statement.

Assume you have a package with a given height 3 inches and width 5 inches. If the package is rotated 90 degrees, you should swap the values for the height and width. The code below makes an attempt to swap the values stored in two variables h and w, which represent height and width. Variable h should end up with w’s initial value of 5 and w should get h’s initial value of 3. Unfortunately this code has an error and does not work. Use the CodeLens to step through the code to understand why it fails to swap the values in h and w.
1-4-7: Explain in your own words why the ErrorSwap program code does not swap the values stored in h and w.
Swapping two variables requires a third variable. Before assigning h = w , you need to store the original value of h in the temporary variable. In the mixed up programs below, drag the blocks to the right to put them in the right order.
The following has the correct code that uses a third variable named “temp” to swap the values in h and w.
The code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right, then check your solution. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.
After three incorrect attempts you will be able to use the Help Me button to make the problem easier.
Fix the code below to perform a correct swap of h and w. You need to add a new variable named temp to use for the swap.
1.4.2. Incrementing the value of a variable ¶
If you use a variable to keep score you would probably increment it (add one to the current value) whenever score should go up. You can do this by setting the variable to the current value of the variable plus one (score = score + 1) as shown below. The formula looks a little crazy in math class, but it makes sense in coding because the variable on the left is set to the value of the arithmetic expression on the right. So, the score variable is set to the previous value of score + 1.
Click on the Show CodeLens button to step through the code and see how the score value changes.
1-4-11: What is the value of b after the following code executes?
- It sets the value for the variable on the left to the value from evaluating the right side. What is 5 * 2?
- Correct. 5 * 2 is 10.
1-4-12: What are the values of x, y, and z after the following code executes?
- x = 0, y = 1, z = 2
- These are the initial values in the variable, but the values are changed.
- x = 1, y = 2, z = 3
- x changes to y's initial value, y's value is doubled, and z is set to 3
- x = 2, y = 2, z = 3
- Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side.
- x = 1, y = 0, z = 3
1.4.3. Operators ¶
Java uses the standard mathematical operators for addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Arithmetic expressions can be of type int or double. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value. (You may have noticed that + was also used to put text together in the input program above – more on this when we talk about strings.)
Java uses the operator == to test if the value on the left is equal to the value on the right and != to test if two items are not equal. Don’t get one equal sign = confused with two equal signs == ! They mean different things in Java. One equal sign is used to assign a value to a variable. Two equal signs are used to test a variable to see if it is a certain value and that returns true or false as you’ll see below. Use == and != only with int values and not doubles because double values are an approximation and 3.3333 will not equal 3.3334 even though they are very close.
Run the code below to see all the operators in action. Do all of those operators do what you expected? What about 2 / 3 ? Isn’t surprising that it prints 0 ? See the note below.
When Java sees you doing integer division (or any operation with integers) it assumes you want an integer result so it throws away anything after the decimal point in the answer, essentially rounding down the answer to a whole number. If you need a double answer, you should make at least one of the values in the expression a double like 2.0.
With division, another thing to watch out for is dividing by 0. An attempt to divide an integer by zero will result in an ArithmeticException error message. Try it in one of the active code windows above.
Operators can be used to create compound expressions with more than one operator. You can either use a literal value which is a fixed value like 2, or variables in them. When compound expressions are evaluated, operator precedence rules are used, so that *, /, and % are done before + and -. However, anything in parentheses is done first. It doesn’t hurt to put in extra parentheses if you are unsure as to what will be done first.
In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider operator precedence .
1-4-15: Consider the following code segment. Be careful about integer division.
What is printed when the code segment is executed?
- 0.666666666666667
- Don't forget that division and multiplication will be done first due to operator precedence.
- Yes, this is equivalent to (5 + ((a/b)*c) - 1).
- Don't forget that division and multiplication will be done first due to operator precedence, and that an int/int gives an int result where it is rounded down to the nearest int.
1-4-16: Consider the following code segment.
What is the value of the expression?
- Dividing an integer by an integer results in an integer
- Correct. Dividing an integer by an integer results in an integer
- The value 5.5 will be rounded down to 5
1-4-17: Consider the following code segment.
- Correct. Dividing a double by an integer results in a double
- Dividing a double by an integer results in a double
1-4-18: Consider the following code segment.
- Correct. Dividing an integer by an double results in a double
- Dividing an integer by an double results in a double
1.4.4. The Modulo Operator ¶
The percent sign operator ( % ) is the mod (modulo) or remainder operator. The mod operator ( x % y ) returns the remainder after you divide x (first number) by y (second number) so 5 % 2 will return 1 since 2 goes into 5 two times with a remainder of 1. Remember long division when you had to specify how many times one number went into another evenly and the remainder? That remainder is what is returned by the modulo operator.

Figure 2: Long division showing the whole number result and the remainder ¶
In the example below, try to guess what it will print out and then run it to see if you are right.
The result of x % y when x is smaller than y is always x . The value y can’t go into x at all (goes in 0 times), since x is smaller than y , so the result is just x . So if you see 2 % 3 the result is 2 .
1-4-21: What is the result of 158 % 10?
- This would be the result of 158 divided by 10. modulo gives you the remainder.
- modulo gives you the remainder after the division.
- When you divide 158 by 10 you get a remainder of 8.
1-4-22: What is the result of 3 % 8?
- 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number!
- This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8.
- What is the remainder after you divide 3 by 8?
1.4.5. FlowCharting ¶
Assume you have 16 pieces of pizza and 5 people. If everyone gets the same number of slices, how many slices does each person get? Are there any leftover pieces?
In industry, a flowchart is used to describe a process through symbols and text. A flowchart usually does not show variable declarations, but it can show assignment statements (drawn as rectangle) and output statements (drawn as rhomboid).
The flowchart in figure 3 shows a process to compute the fair distribution of pizza slices among a number of people. The process relies on integer division to determine slices per person, and the mod operator to determine remaining slices.

Figure 3: Example Flow Chart ¶
A flowchart shows pseudo-code, which is like Java but not exactly the same. Syntactic details like semi-colons are omitted, and input and output is described in abstract terms.
Complete the program based on the process shown in the Figure 3 flowchart. Note the first line of code declares all 4 variables as type int. Add assignment statements and print statements to compute and print the slices per person and leftover slices. Use System.out.println for output.
1.4.6. Storing User Input in Variables ¶
Variables are a powerful abstraction in programming because the same algorithm can be used with different input values saved in variables.

Figure 4: Program input and output ¶
A Java program can ask the user to type in one or more values. The Java class Scanner is used to read from the keyboard input stream, which is referenced by System.in . Normally the keyboard input is typed into a console window, but since this is running in a browser you will type in a small textbox window displayed below the code. The code below shows an example of prompting the user to enter a name and then printing a greeting. The code String name = scan.nextLine() gets the string value you enter as program input and then stores the value in a variable.
Run the program a few times, typing in a different name. The code works for any name: behold, the power of variables!
Run this program to read in a name from the input stream. You can type a different name in the input window shown below the code.
Try stepping through the code with the CodeLens tool to see how the name variable is assigned to the value read by the scanner. You will have to click “Hide CodeLens” and then “Show in CodeLens” to enter a different name for input.
The Scanner class has several useful methods for reading user input. A token is a sequence of characters separated by white space.
Run this program to read in an integer from the input stream. You can type a different integer value in the input window shown below the code.
A rhomboid (slanted rectangle) is used in a flowchart to depict data flowing into and out of a program. The previous flowchart in Figure 3 used a rhomboid to indicate program output. A rhomboid is also used to denote reading a value from the input stream.

Figure 5: Flow Chart Reading User Input ¶
Figure 5 contains an updated version of the pizza calculator process. The first two steps have been altered to initialize the pizzaSlices and numPeople variables by reading two values from the input stream. In Java this will be done using a Scanner object and reading from System.in.
Complete the program based on the process shown in the Figure 5 flowchart. The program should scan two integer values to initialize pizzaSlices and numPeople. Run the program a few times to experiment with different values for input. What happens if you enter 0 for the number of people? The program will bomb due to division by zero! We will see how to prevent this in a later lesson.
The program below reads two integer values from the input stream and attempts to print the sum. Unfortunately there is a problem with the last line of code that prints the sum.
Run the program and look at the result. When the input is 5 and 7 , the output is Sum is 57 . Both of the + operators in the print statement are performing string concatenation. While the first + operator should perform string concatenation, the second + operator should perform addition. You can force the second + operator to perform addition by putting the arithmetic expression in parentheses ( num1 + num2 ) .
More information on using the Scanner class can be found here https://www.w3schools.com/java/java_user_input.asp
1.4.7. Programming Challenge : Dog Years ¶
In this programming challenge, you will calculate your age, and your pet’s age from your birthdates, and your pet’s age in dog years. In the code below, type in the current year, the year you were born, the year your dog or cat was born (if you don’t have one, make one up!) in the variables below. Then write formulas in assignment statements to calculate how old you are, how old your dog or cat is, and how old they are in dog years which is 7 times a human year. Finally, print it all out.
Calculate your age and your pet’s age from the birthdates, and then your pet’s age in dog years. If you want an extra challenge, try reading the values using a Scanner.
1.4.8. Summary ¶
Arithmetic expressions include expressions of type int and double.
The arithmetic operators consist of +, -, * , /, and % (modulo for the remainder in division).
An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away, essentially rounding down the answer to a whole number.
An arithmetic operation that uses at least one double value will evaluate to a double value.
Operators can be used to construct compound expressions.
During evaluation, operands are associated with operators according to operator precedence to determine how they are grouped. (*, /, % have precedence over + and -, unless parentheses are used to group those.)
An attempt to divide an integer by zero will result in an ArithmeticException to occur.
The assignment operator (=) allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.
During execution, expressions are evaluated to produce a single value.
The value of an expression has a type based on the evaluation of the expression.

IMAGES
VIDEO
COMMENTS
The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is
One way to do this is by introducing a (non- final ) temporary variable, but you said you didn't want to do that.
Support for try-with-resources — introduced in Java 7 — allows us to ... first assignment, even though it's not explicitly marked as final.
Using try/catch blocks assignment. Put the following code (as shown previously) into a file called FileOut.java, compile and run. Note what happens.
The Java try-with-resources construct enables you to have resources like an InputStream or JDBC connection automatically closed when you are
In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be
The try...catch block in Java is used to handle exceptions. In this tutorial, we will learn about ... Here, we are trying to assign a value to the index 10.
More How to: use Java:https://youtube.com/playlist?list=PLZPy7sbFuWViOEeiKXw5QowtC5aHGUHgMProblem://Append elements to the hash set if it is
Print to the console the message, "Assessment 6 - Asserts and Try/Catch." Create a string variable and set its value to null or empty. Make a integer variable
The code below makes an attempt to swap the values stored in two variables h and w, which represent height and width. Variable h should end up with w's initial