You can't put reader.close() between the try and the catch. Either put it in a finally block, or use a try-with-resources. Like,

try (BufferedReader reader = new BufferedReader(new FileReader(filenameIn))) {
    reader.readLine();
    for (int i = 0; i < personArray.length; i++) {
        String[] data = reader.readLine().split("/t"); // <-- should be \\t for tab.
        personArray[i] = new Person(Integer.parseInt(data[0]), data[1], 
                data[2], Integer.parseInt(data[3]));
    }
} catch (IOException e) {
    System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
    System.out.println("ERROR" + e.toString());
}

or with the finally block,

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader(filenameIn));
    reader.readLine();
    for (int i = 0; i < personArray.length; i++) {
        String[] data = reader.readLine().split("\\t"); // <-- to split on tab.
        personArray[i] = new Person(Integer.parseInt(data[0]), 
                data[1], data[2], Integer.parseInt(data[3]));
    }
} catch (IOException e) {
    System.out.println("ERROR: WRONG FILE " + e.toString());
} catch (Exception e) {
    System.out.println("ERROR" + e.toString());
} finally {
    if (reader != null) {
        reader.close();
    }
}
Answer from Elliott Frisch on Stack Overflow
🌐
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 - Why write Try-With-Resources without Catch or Finally? - Stack Overflow
Why write Try without a Catch or Finally as in the following example? protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOExc... More on stackoverflow.com
🌐 stackoverflow.com
language agnostic - Why use try … finally without a catch clause? - Software Engineering Stack Exchange
The classical way to program is with try ... catch. When is it appropriate to use try without catch? In Python the following appears legal and can make sense: try: #do work finally: #do some... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
January 23, 2012
java - Im getting an error as try' without 'catch', 'finally' or resource declarations , how can I resolve this in my below code - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
connection pooling - Error java:38: error: 'try' without 'catch', 'finally' or resource declarations - Stack Overflow
I keep getting an error stating I need a catch clause to accompany the try (inside public Connection getConnection()). I dont understand why the compiler isn't noticing the catch directly under the... More on stackoverflow.com
🌐 stackoverflow.com
April 10, 2018
🌐
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 - Catch is ONLY optional if there are no statements inside the try that could throw an exception or you've decided to declare the method as throwing the exception. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 ...
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

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.

🌐
IncludeHelp
includehelp.com › java › can-we-have-a-try-block-without-catch-or-finally-block-in-java.aspx
Can we have a try block without catch or finally block in Java?
A try block must have either a catch or a finally block. If you do not use catch or finally, code will generate an error "'try' without 'catch', 'finally' or resource declarations".
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 - It runs even if an exception is thrown or a return statement is used, making it useful for tasks like closing files, releasing memory, or shutting down connections. The way Java compiles and executes finally guarantees that it always runs before control leaves the method, even when multiple finally blocks are involved. While catch is helpful for handling errors, it’s not always needed when the main goal is making sure resources are cleaned up properly.
🌐
Stack Overflow
stackoverflow.com › questions › 49744345 › error-java38-error-try-without-catch-finally-or-resource-declarations
connection pooling - Error java:38: error: 'try' without 'catch', 'finally' or resource declarations - Stack Overflow
April 10, 2018 - package crud.data; import java.sql.*; import javax.sql.DataSource; import javax.naming.InitialContext; import javax.naming.NamingException; public class ConnectionPool { private static ConnectionPool pool = null; private static DataSource dataSource = null; private ConnectionPool() { try { InitialContext ic = new InitialContext(); dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/acm14n"); } catch (NamingException e) { System.out.println(e); } } public static synchronized ConnectionPool getInstance() { if(pool == null) { pool = new ConnectionPool(); } return pool; } public Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { System.out.println(e); return null; } } public void freeConnection(Connection c) { try { c.close(); } catch (SQLException e) { System.out.println(e); } } }
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
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.
🌐
B4X
b4x.com › home › forums › b4i - ios › ios questions
Travelling compile error | B4X Programming Forum
December 7, 2023 - The Error. shell\src\com\wzl\gk\b4i_main_subs_0.java:3735: error: 'try' without 'catch', 'finally' or resource declarations try { ^ 1 error is generated at subs that previously caused no problems.
🌐
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.
🌐
Scala Users
users.scala-lang.org › question
Using `try`/`finally` without `catch` - Question - Scala Users
June 22, 2020 - If I need to compute something but do some side effect before returning that value, is the correct idiom try/finally without catch · Yes. Actually both finally and catch blocks are optional and you can have a standalone try, but that wouldn’t make sense: · A try without a catch or finally ...
🌐
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).
🌐
Baeldung
baeldung.com › home › java › core java › java – try with resources
Java - Try with Resources | Baeldung
May 11, 2024 - As shown above, the scanner variable is declared final explicitly, so we can use it with the try-with-resources block. Although the writer variable is not explicitly final, it doesn’t change after the first assignment. So, we can to use the writer variable too. In this article, we discussed how to use try-with-resources and how to replace try, catch, and finally with try-with-resources.
🌐
CopyProgramming
copyprogramming.com › howto › java-try-without-catch-and-finally-java
Java: Java's try block without catch and finally clause
March 23, 2023 - Why write Try-With-Resources without Catch or Finally?, In this example the resource is BufferReader object as the class implements the interface java.lang.AutoCloseable and it will be closed whether
🌐
Substack
alexanderobregon.substack.com › p › java-scope-part-4-try-with-resources
Java Scope, Part 4 — try-with-resources and Catch Blocks
May 18, 2025 - That second exception gets tucked away, and you can still pull it out during debugging. Java wants you to have the full story without needing extra tricks. When you declare a resource in the try header, it’s only around for the try block. You won’t be able to use it in catch or finally, and Java closes it for you right after that block runs.
🌐
DEV Community
dev.to › werliton › why-i-use-try-with-finally-without-catch-and-why-this-isnt-weird-code-2j92
Why I Use try with finally Without catch (and Why This Isn’t “Weird Code”) - DEV Community
1 week ago - When it finishes — no matter how — that resource must be released.” · That’s the key idea. No — and this difference matters a lot. ... Without finally, cleanup is best-effort, not guaranteed. # without finally function patrol() { try { return } releaseHallway() }