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);
Answer from sinθ on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
The 'try catch' is finished. Try it Yourself » · The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:
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.

Discussions

Try/Catch inside Try/Catch? (Java Netbeans)
Show the code More on reddit.com
🌐 r/learnprogramming
11
2
June 11, 2023
java - What to put in a try/catch? - Software Engineering Stack Exchange
Note on the question: this is not a duplicate, Efficient try / catch block usage? was asked after this one. The other question is the duplicate. I was wondering what was the best way to use try/ca... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
June 9, 2011
How to code a repetitive respond in a Try/Catch? - Java - Code with Mosh Forum
New learner. I am learning try/catch today. It’s a simple code asking to enter a number and if it’s not a number, I want to ask the user another time to add a number. Can I add a code repeat asking user to add a number if they keep putting the non-number input with a try/catch? More on forum.codewithmosh.com
🌐 forum.codewithmosh.com
0
January 14, 2022
What should be inside try (on try-catch)?
Use e.printStackTrace(System.out) to actually get stack trace in try catch More on reddit.com
🌐 r/learnjava
3
1
September 18, 2021
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-try-catch-block
Java Try Catch Block - GeeksforGeeks
June 3, 2025 - Example: Here, we demonstrate the working try catch block with multiple catch statements. ... import java.util.*; class Geeks { public static void main(String[] args) { try { // ArithmeticException int res = 10 / 0; // NullPointerException String s = null; System.out.println(s.length()); } catch (ArithmeticException e) { System.out.println( "Caught ArithmeticException: " + e); } catch (NullPointerException e) { System.out.println( "Caught NullPointerException: " + e); } } }
🌐
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 ...
🌐
CodeHS
codehs.com › tutorial › david › try-catch-in-java
Tutorial: Try Catch In Java | CodeHS
This tutorial covers the basics of try and catch statements in Java.
🌐
Reddit
reddit.com › r/learnprogramming › try/catch inside try/catch? (java netbeans)
r/learnprogramming on Reddit: Try/Catch inside Try/Catch? (Java Netbeans)
June 11, 2023 -

This is probably going to be a big one, but I am 100% stuck here and my teacher has elected too offer no help whatsoever.

I as a beginner am currently trying to write a program that calculated "Tax Payable" based on earnings. To do so, I have to get an application to read lines from a .txt file, find the third part of each string separated by commas (part of an array, I think), convert it into a double and do calculations on it before writing the new information into a new document.

To do this we had been taught to have a Try/Catch for the read/write because otherwise it doesn't work, and a Try/Catch to try convert the String into a Double. Unfortunately, having a Try/Catch inside a Try/Catch just makes the code ignore the second instance of the command.

I've exhausted every idea I can think of and my teacher has completely refused to point me in the right direction. If you need to see the code please just let me know and I can add a comment with it in.

Thanks....

Find elsewhere
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › catch.html
The catch Blocks (The Java™ Tutorials > Essential Java Classes > Exceptions)
The following are two exception handlers for the writeList method: try { } catch (IndexOutOfBoundsException e) { System.err.println("IndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }
🌐
DataCamp
datacamp.com › doc › java › try
try Keyword in Java: Usage & Examples
catch (Exception e) { e.printStackTrace(); // Logging the exception } Resource Management: For managing resources like file I/O, consider using the try-with-resources statement introduced in Java 7.
🌐
Zero To Mastery
zerotomastery.io › blog › try-catch-java
Beginner's Guide To Try And Catch In Java | Zero To Mastery
Now that you understand the goal of try and catch, let’s go deeper and look at some other situations, such as what would you do if multiple things can go wrong at once?... Errors rarely happen in isolation. A single block of code can fail in multiple ways, depending on the input, the environment, or just bad luck. ... Let’s say a program divides numbers and accesses an array. Both can go wrong. Java throws the first error it encounters and immediately stops execution.
🌐
BeginnersBook -
beginnersbook.com › home › java › try catch in java – exception handling
Try Catch in Java – Exception handling
May 30, 2024 - Try catch block is used for exception handling in Java. The code (or set of statements) that can throw an exception is placed inside try block and if the exception is raised, it is handled by the corresponding catch block. In this guide, we will see various examples to understand how to use ...
🌐
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 - Learn how Java handles runtime errors using try and catch. This guide explains common exceptions and the mechanics that let your code recover cleanly.
🌐
HWS Math
math.hws.edu › javanotes › c3 › s7.html
Javanotes 9, Section 3.7 -- Introduction to Exceptions and try..catch
This allows us to detect a blank ... the user's input is not a legal number. In this example, it makes sense to simply print an error message, ignore the bad input, and let the program continue....
🌐
CodeGym
codegym.cc › java blog › java exceptions › java try - catch
Java Try - Catch
February 20, 2025 - It’s like a cheat sheet for knowing when and how to wield this Java superpower. Let’s get started! Great question! Use a try-catch block when you suspect something might go wrong in your code—like a sneaky error that could crash your program. Think of it as your safety net. For example, if you’re reading a file and it might not exist, or dividing numbers where zero might sneak in, that’s your cue!
🌐
Baeldung
baeldung.com › home › java › core java › exception handling in java
Exception Handling in Java | Baeldung
May 11, 2024 - If we want to try and handle the exception ourselves, we can use a try-catch block.
🌐
Tutorialspoint
tutorialspoint.com › java › java_try_catch_block.htm
Java Try Catch Block
Here is code segment showing how to use multiple try/catch statements. In this example, we're creating an error by dividing a value by 0.
🌐
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 › java › exceptions-in-java
Java Exception Handling - GeeksforGeeks
If an exception occurs, remaining try code is skipped and JVM searches for a matching catch block. If found, the catch block executes. Control then moves to the finally block (if present). If no matching catch is found, the exception is handled by JVM’s default handler. The finally block always executes, whether an exception occurs or not. Note: When an exception occurs and is not handled, the program terminates abruptly and the code after it, will never execute. In Java, all exceptions and errors are subclasses of the Throwable class.
Published   4 weeks ago
🌐
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 ... 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 ....
🌐
Code with Mosh
forum.codewithmosh.com › java
How to code a repetitive respond in a Try/Catch? - Java - Code with Mosh Forum
January 14, 2022 - New learner. I am learning try/catch today. It’s a simple code asking to enter a number and if it’s not a number, I want to ask the user another time to add a number. Can I add a code repeat asking user to add a number i…