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.
🌐
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 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.

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/learnjava › try-with-resources is not as well-known?
Try-with-resources is not as well-known? : r/learnjava
March 17, 2022 - Try with resources was introduced with java 7, but variable assignment with var in 10. OP probably uses java 8. ... it also prevents the need for an additional try catch in the finally to close it, as a lot of close methods throw an exception.
🌐
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).
Find elsewhere
🌐
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 - As an aside, I would allow the getConnection() to throw the SQLException. Otherwise, in whatever code you have, you will end up checking to see if the returned value is null. IMHO, this paradigm clutters the code. Catch the (essentially) unrecoverable exception rather than attempting to check for null everywhere.
🌐
Reddit
reddit.com › r/learnprogramming › what is the purpose of the "finally" block in try/catch/finally exception handling?
What is the purpose of the "finally" block in try/catch/finally exception handling? : r/learnprogramming
January 1, 2024 - If an exception is raised while dealing with a resource that requires closing/freeing (files, sockets, etc), you can put a call to, for example .close() in the finally to ensure that the resources are closed. You can even just use a try...finally without a catch to allow exceptions to propagate, ...
🌐
Reddit
reddit.com › r/learnpython › is it okay to use try/finally without except?
r/learnpython on Reddit: Is it okay to use try/finally without except?
February 12, 2016 -

Hi and sorry for the noob question,

I am calling another python script as a subprocess. The python script tries to do X, and if/when it fails it MUST do Y. I had originally been handling this by doing the following:

 try:
    x
except:
   <code to be run>

For what I want to do, would it be better to simply use:

try:
    x
finally:
    y

If I understand correctly, I am basically using except for something finally should be used for at the moment, yes? Is there any downside to not using except for what I want to accomplish?

Top answer
1 of 4
8
Code after finally will be called whether the code after the try works or not. It doesn't care. Gets called every time. If you need something to run IF AND ONLY IF the code in the try FAILS, then you need to use except.
2 of 4
1
try will attempt a piece of code. If that results in exception, you can capture and handle that exception within except. Whether or not an exception occurred, you can run code in a finally block to guarantee that it runs in all circumstances. That way, even if the exception stops the program, code in the finally block will still execute. For your purpose, you may want to have all three in place: try: # try this code which may cause an Exception except AThingHappened as e: # handle the exception finally: # code that occurs whether exception happened or not. When you run code in the except block, it's possible to prevent that exception from stopping your program. This is a good way to handle common errors, such as the one you're expecting when you run your subscript. If you want, you can choose to raise the exception again from inside the except block, which lets it bubble up through the program until something else catches it or the thread ceases execution. In either case, any code in finally will be run. This is useful for some code that might do some clean up, like closing a connection. To more directly answer your question, if you omit the except block, your code in finally will still run, but you won't be handling the exception. Instead, that exception will be raised and you'll see its traceback in the console. If you have some logic you want to use to handle that exception, use an except statement. However, depending on your use-case, you might do better designing something that can work with the with statement . I don't know the specifics of your program, so I can't say if it would be helpful, but it's worth considering before trying to make something that's overly complex using try..except..finally.
🌐
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.
🌐
Reddit
reddit.com › r/learnjava › purpose of “finally”?
r/learnjava on Reddit: Purpose of “finally”?
December 16, 2023 -

Maybe I’m just too early in learning Java to understand the reason you’d use it and for my purposes it’s irrelevant, but I’m curious.

I know it executes regardless of whether an exception is caught but doesn’t the code below a try {} catch {} block also execute regardless of whether an exception is caught? Isn’t that PART of the point of catching the exception? For the code to continue?

Forgive my ignorance, as there may be some serious misunderstandings of concepts in this post.

Thank you.

Top answer
1 of 8
8
finally is useful if you want to run a bit of code regardless of whether you catch an exception, rethrow an exception, or don't catch an exception at all. Examples include closing resources like files regardless of whether you succeed or error. FileOutputStream stream = new FileOutputStream(...); try { // do stuff with stream that might throw an IOException } finally { // if we throw an exception of any kind, or if we succeed without // an issue, then this always gets run stream.close(); } A long time ago, Java introduced the AutoCloseable and Closable interfaces which let you do this in a bit cleaner way, which looks like this: try (FileOutputStream stream = new FileOutputStream(...)) { // do stuff with stream that might throw an IOException } This does the same thing as my first code block, but is called a "try with resources" and works on anything that implements AutoCloseable or Closeable. Notice I didn't catch any exception. I'm simply specifying that I always want it to do something whether I throw an exception or not. You can mix this with catch blocks if you want in more complex situations too. Also worth noting if you return in a try block, the finally will still get run. try { return 123; } finally { System.out.println("yeet"); }
2 of 8
6
Because sometimes you don't want the code to continue. A lot of the time we log the error and throw a new one to stop the process. Because t still need to close files and other things either way. That's what the finally is for.
🌐
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 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.
🌐
Reddit
reddit.com › r/csharp › regarding try/catch block's finally keyword in c#
r/csharp on Reddit: Regarding try/catch block's finally keyword in C#
May 12, 2024 -

Okay, so I am very familiar with try and except (or catch in c# I guess), but the one I am not sure about is the finally keyword used like:

finally

{

Console.WriteLine("This worked anyway");

}

I understand that this is supposed to run regardless if the Try or Except worked, but the question I have (and also sort of the problem I have with this) is whatever you are doing in this, couldn't you also just do outside of the try/catch block of code? I'm not entirely sure why this is necessary in C# (or in any language). Can someone please explain why we need this.

🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
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.