🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
The technical term for this is: Java will throw an exception (throw an error). 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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-try-catch-block
Java Try Catch Block - GeeksforGeeks
June 3, 2025 - The code inside the try block is executed, and if any exception occurs, it is then caught by the catch block. Example: Here, we are going to handle the ArithmeticException using a simple try-catch block.
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › catch.html
The catch Blocks (The Java™ Tutorials > Essential Java Classes > Exceptions)
This feature can reduce code duplication and lessen the temptation to catch an overly broad exception. In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|): catch (IOException|SQLException ex) { logger.log(ex); ...
🌐
Medium
medium.com › @AlexanderObregon › java-exception-handling-throws-vs-try-catch-94b0abe1080d
Java Exception Handling — Throws vs. Try-Catch
March 17, 2024 - A try-catch block is made up of two main components: The try block: Contains the code that might throw an exception. By placing this code within a try block, you're indicating to the Java runtime that you want to attempt to execute this code, ...
🌐
Jenkov
jenkov.com › tutorials › java-exception-handling › basic-try-catch-finally.html
Basic try-catch-finally Exception Handling in Java
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....
🌐
Wikibooks
en.wikibooks.org › wiki › Java_Programming › Throwing_and_Catching_Exceptions
Throwing and Catching Exceptions - Wikibooks, open books for an open world
This can be handled in two ways: a try-catch block, which will handle the exception within the method and a throws clause which would in turn throw the exception to the caller to handle. The above example will cause a compilation error, as Java is very strict about exception handling.
Find elsewhere
🌐
Software Testing Help
softwaretestinghelp.com › home › java › try, catch, finally and throw in java with examples
Try, Catch, Finally And Throw In Java With Examples
April 1, 2025 - In the signature of this testMethod, we declare two exceptions IOException and Arithmetic Exception using the throws keyword. Then in the main function, the exceptions thrown are handled by the catch block.
🌐
JetBrains
blog.jetbrains.com › idea › 2024 › 03 › easy-hacks-how-to-throw-java-exceptions
Easy Hacks: How to Throw Java Exceptions | The IntelliJ IDEA Blog
March 12, 2024 - When an exception occurs, the Java runtime stops the execution of the current method and passes the exception object to the nearest catch block that can handle it. To throw an exception, you can use the throw keyword followed by the exception object.
🌐
TutorialsPoint
tutorialspoint.com › what-is-the-difference-between-throw-e-and-throw-new-exception-e-in-catch-block-in-java
What is the difference between throw e and throw new Exception(e) in catch block in java?
When an exception raised inside a try block, instead of terminating the program JVM stores the exception details in the exception stack and proceeds to the catch block. A catch statement involves declaring the type of exception you are trying to catch.
🌐
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
Top answer
1 of 2
6

Catch and re-throw.

try {
   ... same as before ...
} catch (ClassAlreadyRegisteredException | ProfessorNotFoundException e) {
    throw e;
} catch (Exception e) {
    // if there is any other error during the communication with the database, 
    // throw a generic IOException
    throw new ClassIOException();
}

Alternatively, remember the exception to throw it later.

 Exception fail = null;

 try {
      ….
     // save exception in place of existing throws
     // for example:
     fail = new ClassAlreadyRegisteredException();
     …
 } catch (Exception ex) {
     ...same as original...
 }

 if (fail != null) {
     throw fail;
 }

I use both techniques; the choice depends on what is simpler in any given situation. Neither is uncontestably better.

For the catch and re-throw method, you have to keep the list of caught-and-rethrown exceptions consistent with the exceptions you actually throw from within the try-clause. In larger cases, I'd avoid that problem by using an exception hierarchy, so I could catch the common base class.

For the save-and-throw method, you have to arrange control flow so that nothing significant is done after detecting the failure, since you don't have the immediate 'throw' command to exit the try-clause. Nevertheless there are cases where it is simple enough; the original example is one such.

2 of 2
2

Checked vs Unchecked Exceptions

It's totally acceptable to throw an exception in a catch block. A common use case is to take a checked Exception and throw a unchecked RuntimeException which would allow the exception bubble up to where it needs to be handled.

You'll want to use checked exceptions for use cases such as Connectivity/IO, SQL exceptions..

Handling Checked Exceptions

To answer your question, in most libraries that connect to the database, an checked IOException is thrown if there are any connectivity issues. For these cases, you can always specify this in the method signature public Class createClass() throws IOException

this specifies that any callers of createClass() has to fulfill the contract that the IOException is handled.

or

You can rethrow this as a RuntimeException

try {
   ...
} catch (IOException e) {
   throw new RuntimeException(e); // <- send the original exception so you can preserve the exception and stacktrace.
}

This will essentially bubble up to STDOUT or whatever handler your framework specifies.

CAUTION:

However, catching an cover all Exception and throwing a more specific ClassIOException can have unintended consequences.

If you have a NullPointerException this will be captured by your catch (Exception e) block and rethrown as a ClassIOException

Doing this will corrupt the stacktrace and cause your error logs to be much more difficult to debug.

Understanding what constitutes an checked Exceptions.

Another tip is to consider what your Exception cases are.

If they are standard flow of the application, service, or business logic -- these may not be appropriate exceptions.

The ClassAlreadyRegisteredException and ProfessorNotFoundException may not be exceptional cases in your application... unless these are already specified by your professor.

Sometimes these can be thrown as RuntimeException if the situation calls for it.

Best Practices?

There are still many opinions on how exceptions are handled. So here are some rule of thumb questions I ask myself when working with exceptions

  1. Is the stacktrace preserved? Will I be able to trace back to the root Exception
  2. Is this common logic and represents an exceptional case that deviates from what my application provides?
  3. If I throw this exception, is it an absolute necessity for anything calling this method to handle this exceptional logic?
🌐
Reddit
reddit.com › r/learnjava › throwing an exception and catching it within the same method? is this bad practice?
r/learnjava on Reddit: Throwing an exception and catching it within the same method? Is this bad practice?
December 22, 2022 -

Hi

I'm not actually new to Java. but I want to make sure I'm following the correct practice

I have this method

public Response processRequest(XMLDocument document) {
    try {
        if (document.process().idFieldIsMissing())
            throw new RuntimeException("error: id field missing from message");

        if (document.process().importantHeaderIsMissing())
            throw new RuntimeException("error: important header is missing");

         if (more validation...)
          throw new RuntimeException()...

        return SuccessResponse("document is valid");

    } catch (Exception e) {
      return FailureResponse(e.getMessage());
    }
}

the basic gist is, I throw an exception in the method, and catch that exception in the very same method.

my reasoning is, I'd rather have one failure return statement in the catch block, then have multiple "return FailureResponse()" for each validation check.

🌐
Rollbar
rollbar.com › home › how to throw exceptions in java
How to Throw Exceptions in Java | Rollbar
2 weeks ago - Throws is a keyword used to indicate that this method could throw this type of exception. The caller has to handle the exception using a try-catch block or propagate the exception.
🌐
IBM
ibm.com › support › pages › best-practice-catching-and-re-throwing-java-exceptions
Best Practice: Catching and re-throwing Java Exceptions
What is the correct Java™ programming best practice to catch, print, and re-throw Java exceptions?
🌐
Quora
quora.com › What-will-happen-if-catch-block-contains-an-exception-in-java
What will happen if catch block contains an exception in java? - Quora
Answer (1 of 4): It will throw an exception and will stop the execution of program. Its very simple concept ,exception thrown in try block will be catched by its subsequent catch blocks but if exception occur in catch block ,then you need to write a separate try catch block in order to catch i...
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › throwing.html
How to Throw Exceptions (The Java™ Tutorials > Essential Java Classes > Exceptions)
As you can see, Throwable has two direct descendants: Error and Exception. The Throwable class. When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors.