As explained above this is a feature in Java 7 and beyond. try with resources allows to skip writing the finally and closes all the resources being used in try-block itself. As stated in Docs

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

See this code example

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example the resource is BufferReader object as the class implements the interface java.lang.AutoCloseable and it will be closed whether the try block executes successfully or not which means that you won't have to write br.close() explicitly.

Another important thing to notice here is that if you are writing the finally block yourself and both your try and finally block throw exception then the exception from try block is supressed.

While on the other hand if you are using try-with-resources statement and exception is thrown by both try block and try-with-resources statement then in this case the exception from try-with-resources statement is suppressed.

As the @Aaron has answered already above I just tried to explain you. Hope it helps.

Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Answer from Syed Ali Taqi on Stack Overflow
Top answer
1 of 2
90

As explained above this is a feature in Java 7 and beyond. try with resources allows to skip writing the finally and closes all the resources being used in try-block itself. As stated in Docs

Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

See this code example

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example the resource is BufferReader object as the class implements the interface java.lang.AutoCloseable and it will be closed whether the try block executes successfully or not which means that you won't have to write br.close() explicitly.

Another important thing to notice here is that if you are writing the finally block yourself and both your try and finally block throw exception then the exception from try block is supressed.

While on the other hand if you are using try-with-resources statement and exception is thrown by both try block and try-with-resources statement then in this case the exception from try-with-resources statement is suppressed.

As the @Aaron has answered already above I just tried to explain you. Hope it helps.

Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

2 of 2
13

This is a new feature in Java 7 and beyond. Without this, you'd need a finally block which closes the resource PrintWriter out. So the code above is equivalent to:

PrintWriter out = null;
try {
    PrintWriter out = ...
} finally {
    if(null != out) {
        try {
            out.close();
        } catch(Exception e) {} // silently ignore!
    }
}

See The try-with-resources Statement

🌐
Reddit
reddit.com › r/javahelp › need help solving 'try' without 'catch', 'finally' or resource declarations error.
r/javahelp on Reddit: Need help solving 'try' without 'catch', 'finally' or resource declarations error.
May 5, 2022 -

I keep receiving this error: 'try' without 'catch', 'finally' or resource declarations. I’ve tried to add and remove curly brackets, add final blocks, and catch blocks and nothing is working.

https://codepen.io/angelineb/pen/KKQpbqV

Top answer
1 of 3
2
OK, it took me a bit to unravel your code because either you've done a great job of obfuscating your own indentation, or codepen absolutely demolished it. So the issue is where you've done try {/ serverSocket = new ServerSocket(1098,500); This try block exists, but it has no catch or finally. Try blocks always have to do one of three things, catch an exception, terminate with a finally (This is generally to close resources like database connections, or run some code that NEEDS to be executed regardless of if an error occurs), or be a try-with-resources block (This is the Java 7+ way of closing resources, like file readers). This block currently doesn't do any of those things. So I would question then is it actually a needed try block? If so, you need to complete it. If not, you need to remove it.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
Discussions

Java Try Catch Finally blocks without Catch - Stack Overflow
I'm reviewing some new code. The program has a try and a finally block only. Since the catch block is excluded, how does the try block work if it encounters an exception or anything throwable? D... More on stackoverflow.com
🌐 stackoverflow.com
Does anyone use the catch and try keywords on java?
You're looking at this though an extremely narrow lens. try/catch isn't for debugging purposes. It's so you can handle errors programmatically. They're useful when you don't want your program to just crash and print an error message. For example, if I was writing an application that had to call some external web API, I don't want the program to crash if that API is offline. I want to try to call the API, and catch any errors, so I can display a nice error message to the user and inform them of the problem, instead of just having the program crash and the user have no idea what to do about it. In short, you're thinking about this from a "how can I figure out what this error is", but the point of the feature is "I know that an error could happen here, this is the code to handle that error". More on reddit.com
🌐 r/learnprogramming
35
7
September 6, 2022
Should try/catch be avoided or used?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
14
3
January 10, 2024
Why do people catch exceptions just to throw it?
This example is also making it lose its original stack trace, making debugging harder: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2200 More on reddit.com
🌐 r/dotnet
86
73
January 18, 2023
Top answer
1 of 9
182

It depends on whether you can deal with the exceptions that can be raised at this point or not.

If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.

If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

2 of 9
40

The finally block is used for code that must always run, whether an error condition (exception) occurred or not.

The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.

The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.

Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.

🌐
Java2Blog
java2blog.com › home › core java › exception handling › can we have try without catch block in java
Can We Have Try without Catch Block in Java - Java2Blog
February 19, 2024 - In Java, it’s possible to use a try block without a catch block, but it must be followed either by a finally block or be part of a try-with-resources statement.
🌐
TutorialsPoint
tutorialspoint.com › article › can-we-have-a-try-block-without-a-catch-block-in-java
Can we have a try block without a catch block in Java?
November 21, 2023 - Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System.exit() it will execute always.
🌐
JanBask Training
janbasktraining.com › community › java › how-can-i-use-java-try-without-catch
How can I use Java try without catch? | JanBask Training Community
October 12, 2022 - When is it appropriate to use try without catch? In Python the following appears legal and can make sense: ... #do work finally: #do something unconditional However, the code didn't catch anything. Similarly one could think in Java it would be as follows: try { //for example try to get a database connection } finally { //closeConnection(connection) }
Find elsewhere
🌐
Medium
medium.com › @AlexanderObregon › how-javas-try-finally-blocks-work-without-catch-96e93be92ae5
How Java’s try-finally Blocks Work Without catch | Medium
March 4, 2025 - The inner finally block runs first before the program exits the inner try-finally, and then the outer finally block runs before the exception leaves main(). The finally block in Java is often used to handle cleanup tasks that must happen regardless ...
🌐
Coderanch
coderanch.com › t › 782298 › java › resources-catch-block-compiler-error
try-with-resources without catch block gets me compiler error (Java in General forum at Coderanch)
June 14, 2024 - Carey Brown wrote:If you have a statement that could throw an exception you need to either declare the method as throwing the exception or surround it with a 'try' and appropriate 'catch'. In 'try-with-resources' if you have a statement that could throw an exception, the same rule applies.
🌐
Medium
medium.com › @sureshkumar_95502 › try-without-catch-java-f4401eaaafa1
try without catch Java. In Java Exception handling, is try… | by Suresh Kumar | Medium
December 13, 2024 - A method whichever calls above method is responsible to have try and corresponding catch to handle the Exception occurred. Click Here to Learn Core Java with 40 Hours of Video, Downloadable Source code examples, total about 120 hours of Learning ... public class TryFinallyExample { public static void main(String[] args) { try { invokeMethod(); } catch (Exception e) { // Handle the exception here System.out.println("Exception caught in main: " + e.getMessage()); } } // This method uses try with finally but no catch block public static void invokeMethod() throws Exception { try { // Some statements here System.out.println("Inside try block."); // throw an Exception throw new Exception("An error occurred in invokeMethod."); } finally { // The finally block is always executed System.out.println("Finally block executed."); } } }
🌐
Quora
quora.com › Can-try-be-used-without-catch
Can try be used without catch? - Quora
In many programming languages a try block can be used without an accompanying catch block, provided it is paired with a finally (or equivalent) construct that guarantees cleanup. Whether this is allowed and how it behaves depends on the language.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed. 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.
🌐
Medium
medium.com › @ByteCodeBlogger › tricky-interview-question-can-you-write-a-try-block-without-catch-ab346a0a4748
Tricky Interview Question — Can you write a TRY block without CATCH? | by Full Stack Developer | Medium
December 14, 2024 - try { // Code that may throw an ... is typically used when you want to ensure some resource is cleaned up (e.g., closing a file, releasing a lock) without explicitly handling the exception in the catch block. import ...
🌐
Sololearn
sololearn.com › en › Discuss › 1379946 › can-be-a-try-block-without-catch
Can be a try block without catch? | Sololearn: Learn to code for FREE!
July 1, 2018 - java · 1st Jul 2018, 4:42 AM · ... you write try then you need to write either catch or finally block. so You can use finally instead of catch but that way your program is going to terminate abruptly since you are not catching ...
🌐
Esdiscuss
esdiscuss.org › topic › try-without-catch-or-finally
try without catch or finally
The lack of parentheses make it clear that the word following 'except' is not the error parameter, and the lack of braces clearly means the catch-phrase ends at the semicolon. It could even be immediately followed by a finally, which I think yields some terse, but useful syntax that's intuitive and consistent. ... Why is the argument and curly brace syntax required for except? Why not simply allow: try { throw ExceptionalException; } catch dosubroutine(); which for the convenience of Jussi's original ask: try { //fail } catch null; (or if you prefer, a noop call).
🌐
javaspring
javaspring.net › blog › java-try-without-catch
Java Try Without Catch: An In-Depth Exploration — javaspring.net
When a try block is used without a catch block, any exceptions that are thrown within the try block will propagate up the call stack. This means that the calling method or the JVM will be responsible for handling these exceptions.
🌐
Simplilearn
simplilearn.com › home › resources › software development › try catch in java
Try Catch in Java - Exception handling (With Examples) | Simplilearn
September 10, 2025 - Catch statements allow you to define a block of code that will be executed if an error occurs within a try block. Find out more about Try Catch in Java.
Address   5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
🌐
GeeksforGeeks
geeksforgeeks.org › try-catch-throw-and-throws-in-java
Java Try Catch Block | GeeksforGeeks
January 2, 2025 - If no matching catch block is found the exception is passed to the JVM default exception handler. The final block is executed after the try catch block.