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

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
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
Java Exception Handling (Try-catch) Discussions | Java | HackerRank
You are viewing a single comment's thread. Return to all comments → · Seems like cookies are disabled on this browser, please enable them to open this website More on hackerrank.com
🌐 hackerrank.com
🌐
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"); } }
🌐
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.
🌐
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 ...
Find elsewhere
🌐
Programiz
programiz.com › java-programming › try-catch
Java try...catch (With Examples)
Become a certified Java programmer. Try Programiz PRO! ... The try...catch block in Java is used to handle exceptions and prevents the abnormal termination of the program.
🌐
CodeGym
codegym.cc › java blog › java exceptions › java try - catch
Java Try - Catch
February 20, 2025 - If no such block is found, an unhandled exception message is displayed to the user and further execution of the program is stopped. It is to prevent such an emergency stop that you need to use the try..catch block. Exception handling in Java is based on the use of the following keywords in a program:
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › basic-try-catch-finally.html
Basic try-catch-finally Exception Handling in Java
October 25, 2022 - If an exception is thrown from ... the call stack to the method that called openFile(). If the calling method has a try-catch block, the exception will be caught there....
🌐
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…
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › try...catch
try...catch - JavaScript | MDN
See the JavaScript Guide for more information on JavaScript exceptions. When an exception is thrown in the try block, exceptionVar (i.e., the e in catch (e)) holds the exception value. You can use this binding to get information about the exception that was thrown.
🌐
Quora
quora.com › How-is-try-catch-different-from-try-finally-in-Java
How is try-catch different from try-finally in Java? - Quora
Answer (1 of 7): The major difference is that the catch block is only executed if an exception occurs, while the finally block is alway executed after the try block. The major value in try-finally is that you can grab a resource in the try block, ...
🌐
YouTube
youtube.com › alex lee
Try Catch Java Tutorial - YouTube
Free preview of my Java course: https://course.alexlorenlee.com/courses/learn-java-fast This is how to use write a try catch statement in java! ✅Hopefully, w...
Published   May 2, 2019
Views   34K
🌐
Zero To Mastery
zerotomastery.io › blog › try-catch-java
Beginner's Guide To Try And Catch In Java | Zero To Mastery
Since checked exceptions are unavoidable, Java requires developers to handle them themselves, because if they aren’t caught, the program will crash. That’s exactly what try and catch are for. We can assume errors will happen and engineer solutions in advance.
🌐
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 ...
🌐
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 .
🌐
DataCamp
datacamp.com › doc › java › try
try Keyword in Java: Usage & Examples
The try keyword in Java is used to define a block of code that will be tested for exceptions while it is being executed. The try block is usually followed by one or more catch blocks, which handle specific exceptions that may be thrown within the try block.
🌐
Tutorialspoint
tutorialspoint.com › java › java_try_catch_block.htm
Java Try Catch Block
When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. A method catches an exception using a combination of the try and catch keywords.