The implicit invocation of close on your PrintWriter will actually close the underlying Writer as well.

See following example:

StringWriter sw = new StringWriter() {
        @Override
        public void close() throws IOException {
            super.close();
            System.out.println("closed");
        }
};
try (PrintWriter pw = new PrintWriter(sw)) {};

Output

closed
Answer from Mena on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
Exception handling lets you catch and handle errors during runtime - so your program doesn't crash. ... The try statement allows you to define a block of code to be tested for errors while it is being executed.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › catch.html
The catch Blocks (The Java™ Tutorials > Essential Java Classes > Exceptions)
The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if ...
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › tryResourceClose.html
The try-with-resources Statement (The Java™ Tutorials > Essential Java Classes > Exceptions)
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 is a try statement that declares one or more resources.
🌐
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
🌐
Coderanch
coderanch.com › t › 776544 › java › Assign-local-variable-catch-block
Assign value to local variable from try/catch block (Beginning Java forum at Coderanch)
No, catching an exception only to return a special value is not okay. Just let the exception propagate up the call stack and let the caller deal with it.
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › basic-try-catch-finally.html
Basic try-catch-finally Exception Handling in Java
This text summarizes the basics of how try-catch-finally clause error handling works. The examples are in Java, but the rules are the same for C#. The only difference between Java and C# exceptions is that C# doesn't have checked exceptions.
🌐
Programiz
programiz.com › java-programming › try-catch
Java try...catch (With Examples)
Here, we are trying to assign a value to the index 10. Hence, IndexOutOfBoundException occurs. ... 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. From Java SE 7 and later, we can now catch more than one type of exception with one catch block.
Find elsewhere
🌐
Javatpoint
javatpoint.com › try-catch-block
Java Try-catch block - javatpoint
Java try-catch block. Let's see what is try and catch block and how can we write a simple program of exception handling
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-try-catch-block
Java Try Catch Block - GeeksforGeeks
June 3, 2025 - Example: Here, we are going to handle the ArithmeticException using a simple try-catch block. ... import java.io.*; class Geeks { public static void main(String[] args) { try { // This will throw an ArithmeticException int res = 10 / 0; } // Here we are Handling the exception catch (ArithmeticException e) { System.out.println("Exception caught: " + e); } // This line will executes weather an exception // occurs or not System.out.println("I will always execute"); } }
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › catch-multiple.html
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
October 20, 2025 - The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:
🌐
Quora
quora.com › How-do-I-use-try-catch-in-Java
How to use “try catch” in Java - Quora
Answer (1 of 3): The [code ]try-catch[/code] syntax in Java can be used to handle the [code ]Exception[/code] thrown by a particular method. It is useful for giving a meaningful error log to tell that the particular scenario has an error occurred.
🌐
University of Pennsylvania
cis.upenn.edu › ~bcpierce › courses › 629 › papers › Java-tutorial › java › exceptions › catch.html
The catch Block(s)
try { . . . } catch ( . . . ) { . . . } catch ( . . . ) { . . . } . . . There can be no intervening code between the end of the try statement and the beginning of the first catch statement. The general form of Java's catch statement is:
🌐
HWS Math
math.hws.edu › javanotes › c3 › s7.html
Javanotes 9, Section 3.7 -- Introduction to Exceptions and try..catch
When the computer executes this try..catch statement, it executes statements-1, the statements inside the try part. If no exception occurs during the execution of statements-1, then the computer just skips over the catch part and proceeds with the rest of the program.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › try.html
The try Block (The Java™ Tutorials > Essential Java Classes > Exceptions)
private List<Integer> list; private static final int SIZE = 10; public void writeList() { PrintWriter out = null; try { System.out.println("Entered try statement"); FileWriter f = new FileWriter("OutFile.txt"); out = new PrintWriter(f); for (int i = 0; i < SIZE; i++) { out.println("Value at: " + i + " = " + list.get(i)); } } catch and finally blocks .
🌐
Sololearn
sololearn.com › en › Discuss › 1471228 › why-we-write-e-in-catch-in-java-exceptionwhat-is-the-meaning-of-e
Why we write e in catch in java exception,what is the meaning of e? | Sololearn: Learn to code for FREE!
Your 'catch' block will literally 'catch'' an exception object that was 'thrown' at some point during a 'try' block and store it in the 'e' variable (a.k.a parameter) Inside your catch block, you can choose to throw 'e' again and some higher-level ...
🌐
Coderanch
coderanch.com › t › 385887 › java › catch-block-variable-scope
try catch block and variable scope (Java in General forum at Coderanch)
On the other hand, I apparently need to initialize 'statement' within the try because if I move the initialization outside the try to get the variable 'statement' within scope of everything, i get 'variable may not be initialized' error on the statement.close() in the catch and finally.
Top answer
1 of 4
10

Explanation

From the Java documentation:

[The try block] contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)

An exception is a special kind of object. When you write new Exception(), you are creating a new exception object. When you write throw new Exception() you are creating a new error, and then throwing it to the nearest try-catch block, aborting the rest of your code.

When you throw an exception, it gets caught by the try-catch block that it's nested in (inside of). That is, assuming the proper catch block for that exception is registered. If the code is not wrapped in a try-catch block, the program with automatically shut down as soon as an error is thrown. Use a try-catch around any code or method that can throw an error, especially because of user input (within reason).

Some exceptions have to be caught, others are optional to catch. (checked vs. unchecked).

When you add throws to a method signature, you are announcing to other methods that if they call that method, it has the potential to throw a checked exception (it is not necessary for unchecked). Notice how it's throws not throw. It's not doing an action, it's describing that it sometimes does an action.

You use this functionality when you don't want to catch the error inside that method, but want to allow the method's that call your method to catch the error themselves.

Exceptions are a way to make your program respond coherently to unexpected or invalid situations and are especially useful when user input is required, though it's also useful in other situations such as File input/output.

Examples

public CircleWithException() throws InvalidRadiusException {
       this(1.0);
}

Here, the CircleWithException() has the potential to throw an InvalidRadiusException (presumably, the this(1.0) sometimes throws an InvalidRadiusException.)

The code calling this method should have:

try {
    new CircleWithException(); // This calls the method above
} catch (InvalidRadiusException e) { // The object "e" is the exception object that was thrown.
    // this is where you handle it if an error occurs
}

As I said before, an Exception is just a specific type of object that extends Exception

/* Invalid radius class that contains error code */
public class InvalidRadiusException extends Exception {
     private double radius;

/** Construct an exception */
public InvalidRadiusException(double radius) {
       super("Invalid radius " + radius);
       this.radius = radius;
}

/** Return the radius */
public double getRadius() {
    return radius;
 }
}

The above code defines a new type of Exception specific to your program/application. There are many predefined exceptions in the Java Standard Library, but often you need to create your own.

To throw this exception, you first create an InvalidRadiusException object and then throw it:

throw new InvalidRadiusException(1.0);
2 of 4
3

You can declare a method to throw an exception if you can't (or it's not convinient) to handle the exception inside the method.

In your case, you are calling the method setRadius inside the constructor. If you think that is convinient to handle the exception (that is thrown by setRadius) inside the constructor, you can use a try-catch clause:

public CircleWithException(double newRadius) throws InvalidRadiusException {
    try {
        setRadius(newRadius);
        numberOfObjects++;
    } catch (InvalidRadiusException e) {
        setRadius(0); // for example
    }
}

The catch block contains what you want to do if an exception were thrown. In this case, I'm setting the radius to 0, but you can change this.

Remember that it depends in your classes implementation and how you want them to work. If you don't want the constructor to handle this exception, you can throw it (as you are already doing) and handle it in other methods.

🌐
UTK
web.eecs.utk.edu › ~bvanderz › teaching › guiSp13 › notes › exception-handling.html
java exception handling
Exception Handling in Java A. Exception Handlers 1. Specified using a try-catch clause try { // Code that is expected to raise the exception } catch(type variable_name) { // A handler body } ... catch(type variable_name) { // A handler body } finally { // An optional block of code to be executed regardless of // whether the try block fails or succeeds } 2. catch clauses can have only a single formal parameter a.
🌐
Medium
medium.com › @AlexanderObregon › handling-basic-errors-with-try-and-catch-blocks-in-java-for-beginners-cf248fff543a
Handling Basic Errors With Try and Catch Blocks in Java for Beginners
June 13, 2025 - That might mean printing a message, skipping ahead, or logging what went wrong. The important part is that your code stays in control. This works because Java has a clear system for managing method calls and tracking what went wrong. The try and catch syntax gives you a way to use that system to write code that handles failure cleanly.