In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.


From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?

Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.

Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

  • Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

  • Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.

For detailed information see:

  • Unchecked Exceptions — The Controversy
  • The Catch or Specify Requirement
Answer from Jomoos on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › throw-throws-java
throw and throws in Java - GeeksforGeeks
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. ... Where instance is an object of type Throwable (or its subclasses, such as Exception).
Published   2 weeks ago
Top answer
1 of 9
191

In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.


From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?

Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.

Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

  • Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

  • Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.

For detailed information see:

  • Unchecked Exceptions — The Controversy
  • The Catch or Specify Requirement
2 of 9
35

Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.

For example:

class throwseg1 {
    void show() throws Exception {
        throw new Exception();
    }
}

Should be written as:

class throwseg1 {
    void show() {
        try {
            throw new Exception();
        } catch(Exception e) {
            // code to handle the exception
        }
    }
}

This way you can get rid of the "throws Exception" declaration in the method declaration.

Discussions

java - What does "Throws" do and how is it helpful? - Stack Overflow
I am new to Java and have just came across a tutorial which uses the"Throws" keyword in a method. I have done a little research into this but still do not really understand it. From what I have seen so far, it is telling the compiler that a certain exception may be thrown in that particular method. Why do we need to tell the compiler this? I have made many ... More on stackoverflow.com
🌐 stackoverflow.com
java - Why shouldn't a method throw multiple types of checked exceptions? - Software Engineering Stack Exchange
Also, in books/articles on exception handling, the topic of limiting the number of exceptions thrown is usually not brought up. But many of the examples show throwing/catching multiple giving an implicit approval to the practice. So, I found the rule surprising and wanted to do more research on the best practices/philosophy of exception handling versus just the basic how-to examples. ... This is bad too... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 26, 2014
java - Is "throws Throwable" good practice - Stack Overflow
For example, when you use InputStream, ... methods throw at least java.io.IOException, which gives you some useful information about what you should watch for. When coding, as a general rule, you want to try to keep your APIs as expressive as possible. You've got essentially one line of code to show the public API of a method (i.e. its signature, annotations too I guess), ... More on stackoverflow.com
🌐 stackoverflow.com
exception - How to avoid many try catch blocks in java - Stack Overflow
I'm very new to java and the idea of try catch blocks to handle exceptions. This roughly what I'm ending up with, and there simply has to be a better way: try { JSONObject jsonObject ... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 5
55

You can manage an exception within a method using try and catch as you say. In that case, you do not need to use throws. For example:

public void myMethod()
{
  try {
    /* Code that might throw an exception */
  }
  catch (SpaceInvadersException exception) {
    /* Complicated error handling code */
  }
}

But suppose you had a thousand methods, all of which might throw a SpaceInvadersException. Then you would end up having to write all the complicated error handling code a thousand times. Of course, you could always create an ErrorHandler class with a dealWithSpaceInvadersException() method that you could call from them, but you'd still be stuck with a thousand try-catch blocks.

Instead, you tell the compiler that each of these thousand methods could throw a SpaceInvadersException. Then any method that calls one of these methods needs to deal with the error itself, either by using a try-catch, or by telling the compiler that it might throw a SpaceInvadersException. This is done using the throws keyword, like this:

public void myMethod() throws SpaceInvadersException
{
  /* Code that might throw an exception */
}

public void callingMethod()
{
  try {
    myMethod();
  }
  catch (SpaceInvadersException exception) {
    /* Complicated error handling code */
  }
}

In that case, you need to inform the compiler that myMethod could throw a SpaceInvadersException. This means that you can't call that method without dealing with the exception in some way (try-catch or using the throws keyword on the calling method). If throws weren't there, you could call the method without doing any exception handling, and get an exception that wasn't dealt with anywhere in the program (which would be bad).

Since it is always better to avoid code duplication, it is normally better to palm off your error handling to a try-catch in a much higher level function than it is to deal with it separately in all of the low level methods. That is why this mechanism exists.

2 of 5
6

The throws keyword declares that the exception can be thrown out of the method.

You can also use a catch block to catch an exception inside the method. If you catch it and don't rethrow it, then it's not thrown out of the method.

A throws declaration allows compile-time verification that a method either:

  • Catches the exceptions it throws, including those from the methods it calls.
  • Or declares them, so that its callers can make the same check.
Top answer
1 of 4
34

Lets consider the situation where you have the provided code of:

public void delete() throws IOException, SQLException {      // Non-Compliant
  /* ... */
}

The danger here is that the code that you write to call delete() will look like:

try {
  foo.delete()
} catch (Exception e) {
  /* ... */
}

This is bad too. And it will be caught with another rule that flags catching the base Exception class.

The key is to not write code that makes you want to write bad code elsewhere.

The rule that you are encountering is a rather common one. Checkstyle has it in its design rules:

ThrowsCount

Restricts throws statements to a specified count (1 by default).

Rationale: Exceptions form part of a method's interface. Declaring a method to throw too many differently rooted exceptions makes exception handling onerous and leads to poor programming practices such as writing code like catch(Exception ex). This check forces developers to put exceptions into a hierarchy such that in the simplest case, only one type of exception need be checked for by a caller but any subclasses can be caught specifically if necessary.

This precisely describes the problem and what the issue is and why you shouldn't do it. It is a well accepted standard that many static analysis tools will identify and flag.

And while you may do it according to language design, and there may be times when it is the right thing to do, it is something that you should see and immediately go "um, why am I doing this?" It may be acceptable for internal code where everyone is disciplined enough to never catch (Exception e) {}, but more often than not I've seen people cut corners especially in internal situations.

Don't make people using your class want to write bad code.


I should point out that the importance of this is lessened with Java SE 7 and later because a single catch statement can catch multiple exceptions (Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking from Oracle).

With Java 6 and before, you would have code that looked like:

public void delete() throws IOException, SQLException {
  /* ... */
}

and

try {
  foo.delete()
} catch (IOException ex) {
     logger.log(ex);
     throw ex;
} catch (SQLException ex) {
     logger.log(ex);
     throw ex;
}

or

try {
    foo.delete()
} catch (Exception ex) {
    logger.log(ex);
    throw ex;
}

Neither of these options with Java 6 are ideal. The first approach violates DRY. Multiple blocks doing the same thing, again and again - once for each exception. You want to log the exception and rethrow it? Ok. The same lines of code for each exception.

The second option is worse for several reasons. First, it means that you are catching all the exceptions. Null pointer gets caught there (and it shouldn't). Furthermore, you are rethrowing an Exception which means that the method signature would be deleteSomething() throws Exception which just makes a mess further up the stack as people using your code are now forced to catch(Exception e).

With Java 7, this isn't as important because you can instead do:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Furthermore, the type checking if one does catch the types of the exceptions being thrown:

public void rethrowException(String exceptionName)
throws IOException, SQLException {
    try {
        foo.delete();
    } catch (Exception e) {
        throw e;
    }
}

The type checker will recognize that e may only be of types IOException or SQLException. I'm still not overly enthusiastic about the use of this style, but it isn't causing as bad code as it was under Java 6 (where it would force you to have the method signature be the superclass that the exceptions extend).

Despite all these changes, many static analysis tools (Sonar, PMD, Checkstyle) are still enforcing Java 6 style guides. It's not a bad thing. I tend to agree with a warning these to still be enforced, but you might change the priority on them to major or minor according to how your team prioritizes them.

If exceptions should be checked or unchecked... that is a matter of great debate that one can easily find countless blog posts taking up each side of the argument. However, if you are working with checked exceptions, you probably should avoid throwing multiple types, at least under Java 6.

2 of 4
26

The reason that you would, ideally, want to only throw one type of exception is because doing otherwise likely violates the Single Responsibility and Dependency Inversion principles. Let's use an example to demonstrate.

Let's say we have a method that fetches data from persistence, and that persistence is a set of files. Since we are dealing with files, we can have a FileNotFoundException:

public String getData(int id) throws FileNotFoundException

Now, we have a change in requirements, and our data comes from a database. Instead of a FileNotFoundException (since we are not dealing with files), we now throw an SQLException:

public String getData(int id) throws SQLException

We would now have to go through all code that uses our method and change the exception we have to check for, else the code won't compile. If our method gets called far and wide, that can be a lot to change/have others change. It takes a lot of time, and people aren't going to be happy.

Dependency inversion says that we really shouldn't throw either of these exceptions because they expose internal implementation details we are working to encapsulate. Calling code needs to know what type of persistence we are using, when it really should just be worried about if the record can be retrieved. Instead we should throw an exception that conveys the error at the same level of abstraction as we are exposing through our API:

public String getData(int id) throws InvalidRecordException

Now, if we change the internal implementation, we can simply wrap that exception in an InvalidRecordException and pass it along (or not wrap it, and just throw a new InvalidRecordException). External code does not know or care what type of persistence is being used. It's all encapsulated.


As for Single Responsibility, we need to think about code that throws multiple, unrelated exceptions. Let's say we have the following method:

public Record parseFile(String filename) throws IOException, ParseException

What can we say about this method? We can tell just from the signature that it opens a file and parses it. When we see a conjunction, like "and" or "or" in the description of a method, we know that it is doing more than one thing; it has more than one responsibility. Methods with more than one responsibility are hard to manage as they can change if any of the responsibilities change. Instead, we should break methods up so they have a single responsibility:

public String readFile(String filename) throws IOException
public Record parse(String data) throws ParseException

We've extracted out the responsibility of reading the file from the responsibility of parsing the data. One side effect of this is that we can now pass in any String data to the parse data from any source: in-memory, file, network, etc. We can also test parse more easily now because we don't need a file on disk to run tests against.


Sometimes there really are two (or more) exceptions we can throw from a method, but if we stick to SRP and DIP, the times we encounter this situation become rarer.

Top answer
1 of 9
58

You should not throw Throwable. Here's why.

Throwable is the top of the hierarchy of things that can be thrown and is made up of Exceptions and Errors. Since Errors by definition arise from unsalvagable conditions, it is pointless to include them in your method declaration. That leaves just Exception.

You should declare your method with throws Exception instead.


Note that the narrower the range of throws the better.

Declaring your method to be throws Exception is ok if your method doesn't generate the exceptions, but instead calls other code that is declared as throws Exception and you want exceptions to percolate up the call stack.

If your method is the generating the exception, then declare a narrower range, eg throws IOException, MyProcessingException, etc

2 of 9
9

That's a loaded question. This isn't so much about exception handling as it is about code readability.

It depends where you get your code samples from. Professionals prefer to be more specific when throwing out of a method. The main reason is that it keeps your APIs more readable. For example, if your method throws Throwable, that basically means anything could happen and your method doesn't want to deal with it, no matter what. But really, only a limited number of things could happen:

  • Whatever checked exceptions resulting from other calls you are making in your method
  • Whatever checked exceptions you are throwing on purpose based on your own assertions
  • Whatever unchecked exception you didn't plan for
  • Errors (java.lang.Error) that are more global to the JVM and the environment

By specifically stating the exceptions you want to throw, you are telling the users of your API about what they should beware of. For example, when you use InputStream, you'll notice most methods throw at least java.io.IOException, which gives you some useful information about what you should watch for.

When coding, as a general rule, you want to try to keep your APIs as expressive as possible. You've got essentially one line of code to show the public API of a method (i.e. its signature, annotations too I guess), so you want it completely expressive (return type, name, parameters, but also the thrown exceptions).

As far as catching the throwables and printing the stack trace, I'd say that you should not catch the exception unless you can do something about it. Instead, let it roll up the call stack until some class catches it to do something about it. Sometimes, it may roll all the way up to your main class, which I guess would have to catch it and print the stack trace as last resort. Basically, if you can't act upon the exception, then let it go up the call stack. Also it is extremely rare that you find yourself in a situation where you should silence an exception (i.e. catch it but do nothing about it). That's usually inviting problems when comes time to troubleshoot issues.

Here is a fun but interesting article around misuse of exception handling in general.

Find elsewhere
🌐
Prgrmmng
prgrmmng.com › home › series › java fundamentals › throw vs throws in java – key differences, syntax, and best practices
Throw vs Throws in Java – Key Differences, Syntax, and Best Practices | prgrmmng.com
July 30, 2025 - Frequent use of throw in loops can create performance overhead due to repeated object creation. Declaring too many exceptions in throws can make the API harder to use and maintain.
Top answer
1 of 11
7

If all you're doing is catching them and printing the stack trace regardless of the exception type, you can just wrap the code in one large try/catch block. To save many "catches", you can catch java.lang.Throwable which is the interface that all exceptions implement. If not, you can have a catch for every type of checked exception the code you're calling throws, and handle them specifically.

Eclipse keeps asking you to do so because Java code will not compile if the checked exceptions are not caught, or declared to be thrown by the caller.

+Adding this comment to the answer (Thanks, Paul Tomblin):

In production quality apps you'd be logging the trace, adding some logic where you're handling the exception in a right way, taking an alternate flow, and/or re-wrapping it in another exception and throwing it, etc. It all depends on the particular problem you're trying to solve.

2 of 11
4

The idea of exception handling is that you can handle errors at points in your program flow where you can deal with them meaningfully. Rather than checking every function's return value like in C, where most of the time you can't do anything sensible other than passing the error further up, you install a try/catch block at sensible points in your program:

Basically, whenever there is a point where you can react meaningfully to an error, then catch that error, and pass everything else on. That way, error handling is only invoked when there is a plausible recovery from the error.

For example, worst case if any error stops your program from executing meaningfully, then you might almost not catch anything at all and just let the OS handle the situation (well, perhaps one single try/catch to produce a friendly error message).

Example (in C++, sorry, I'm can't type Java blind):

int main()
{
  try {
    while (masterloop()) { }
  catch (...) {
    LOG("Fatal program error, terminating!"); // nothing else we can do!
  }
}

/* lots of program logic */

void process_image()
{
  try {
    Image im = load_image_from_disk();
    /* ... */
  }
  catch (const OutOfMemoryExc & e) {
    LOG("Not enough memory to process the image.");
    return;
  }
  catch (const DataErrorExc & e) {
    LOG("Could not read the image data.");
    return;
  }
  catch (...) {
    throw; // pass everything else along
  }
}

In this example, we may try to process an image and fail for some anticipable reasons (out of memory, or failure to read the image). In that case we just return without doing work and let the program continue gracefully. All other errors are propagated up to a higher point. Most importantly, we do not need to litter the actual image processing function with error checks and responses all the time, it suffices for any code there to throw one of our two good exceptions and not worry any further.

Moral: If you have try/catch blocks absolutely everywhere, you're doing it wrong.

🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › throwing.html
How to Throw Exceptions (The Java™ Tutorials > Essential Java Classes > Exceptions)
As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program. You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.
🌐
Rollbar
rollbar.com › home › how to use the throws keyword in java (and when to use throw)
When and Why to Use Throw vs Throws in Java Exception Handling | Rollbar
September 16, 2024 - The throws keyword in Java is used to declare exceptions that can occur during the execution of a program. For any method that can throw exceptions, it is mandatory to use the throws keyword to list the exceptions that can be thrown.
🌐
Programiz
programiz.com › java-programming › throw-throws
Java throw and throws Keyword
Refer to Java Exceptions to learn in detail about checked and unchecked exceptions. Usually, we don't need to handle unchecked exceptions. It's because unchecked exceptions occur due to programming errors. And, it is a good practice to correct them instead of handling them. This tutorial will now focus on how to handle checked exceptions using throw and throws.
Top answer
1 of 5
15
Disagree with everyone else here. Obviously, don't do it for unchecked exceptions just because those are straightforward. But some are saying "Fuck that just only throw unchecked exceptions." This is poor practice in my opinion. Modern, reliable code is fail-fast. Part of the fail-fast coding paradigm is having exceptions for possible failure modes of your methods and ensuring they are documented. Writing "Throws XYZException" at the end of a method signature is not that messy or difficult to read. It ensures you document it in-line if you're using Javadoc style documentation (you should), and it makes it crystal clear that the method being called can indeed throw that exception. You want your code to easily detect failures and very clearly lay out the cause of them. Exceptions are a necessity for this. Yes, they're ugly to handle sometimes, but the payoff of well-documenting all sources of error and easily tracing back where a failure occurred is worth it. Yes. Declare that it throws exceptions. Do not make using unchecked exceptions a habit to avoid dealing with writing the word "throws" at the end of your methods. Do not avoid exceptions altogether, they are your friend.
2 of 5
4
tl;dr: Don't do that ;-) Long: Are you aware of the difference between checked and unchecked exceptions? If not: please read about it. In generell I would say using checked exceptions just polutes your sourcecode and thus should be avoided. Use your own (unchecked) exceptions and wrap them where it is required and catch them where it is required. You should have unittests verifying both, correct exceptions being throwen and for those places in your sourcecode where they are handled. In generell it makes sense to try to centralize exception handling (for example via a exception mapper if you are using spring).
Top answer
1 of 5
7

Is it bad practice to throw multiple custom exceptions in Java?

No. It is good practice.

The only situation where multiple exceptions might be a (slightly) bad idea is if there is absolutely no possibility (ever!) of catching individual exceptions; i.e. the fine-grained exceptions won't serve any functional purpose. However, my opinion is that if you can make that assertion, then there is probably something wrong with the way that you / your team is using Java. And the counter-argument is that sensible use of multiple custom exceptions will help you to document the APIs ... even if you are never going to do more than catch-log-and-bail-out at runtime.

This is not to say that lots of custom exceptions will always be good:

  • If you go overboard and create a separate exception for everything, then you are probably adding unnecessary complexity. (In a lot of cases, different exception messages are sufficient.)

  • If you don't have a sensible inheritance hierarchy for your custom exceptions, then you may end up regretting it. (A well-designed hierarchy allows you to catch "classes" of exceptions, or declare methods as throwing them. It can make your code simpler.)

2 of 5
7

Is it bad practice to throw multiple custom exceptions in Java?

Generally speaking: No. Why should it?

As with everything: Abstraction is your friend.

Is it necessarry to have a CustomerNotFound Exception and a ProductNotFound Exception? Or are your requirements just a more abstract NotFoundException? The context could help to determine, what was missing. Having different exceptions for the sake of having them is nonsense.

Is it necessary, each layer of your application having custom exceptions? Exceptions are a way to report, that an intended action failed due to some reason.

  • Say, you have a controller which asks the service-layer to retrieve data, which in turn asks the DA-layer to read values from the DB. The resultset is empty. The service gets the empty resultset and throws a NotFoundException the service communicates, the failure of the action due to a missing result.

  • Say, the controller needs the service to do the payrolls for employees. And the service is asked to do the payroll for the employee with ID 123456, and in turn asks a service to retrieve the employee - but no emloyee could be found.

There are two ways to deal with that:

1) You throw a NotFound exception in the DA-Layer, catch it in the payroll-service and rethrow a PayrollServiceException wrapping the NotFoundException with the message Exmployee could not be found

2) You throw a NotFound exception in the DA-Layer and do not catch it in the payroll service and catch it instead a layer above.

I would go for (2), since in (1) the information, that the action failed because of a missing employee is redundant.

Top answer
1 of 11
72

A method can throw one of several exceptions. Eg:

 public void dosomething() throws IOException, AWTException {
      // ....
 }

This signals that the method can eventually throw one of those two exceptions (and also any of the unchecked exceptions). You cannnot (in Java or in any language AFAIK) throw simultaneously two exceptions, that would not make much sense.

You can also throw a nested Exception, which contains inside another one exception object. But that would hardly count that as "throwing two exceptions", it just represents a single exception case described by two exceptions objects (frequently from different layers).

2 of 11
32

You can't throw two exceptions. I.e. you can't do something like:

try {
    throw new IllegalArgumentException(), new NullPointerException();
} catch (IllegalArgumentException iae) {
    // ...
} catch (NullPointerException npe) {
    // ...
}

Alternative 1: Exception A is caused by exception B

You could nest exceptions using the cause-constructor to do the following:

try {
    Exception ex1 = new NullPointerException();

    // Throw an IllegalArgumentException that "wraps" ex1
    throw new IllegalArgumentException(ex1);
} catch (IllegalArgumentException iae) {
    // handle illegal argument...
    throw iae.getCause(); // throws the cause (the NullPointerException)
}

Good article on chained exceptions: Programming.Guide: Chained Exceptions

Alternative 2: Use suppressed exception

One exception can suppress another exception.

try {
    Exception ex1 = new NullPointerException();
    
    // Throw an IllegalArgumentException that "suppresses" ex1
    IllegalArgumentException ex2 = new IllegalArgumentException();
    ex2.addSuppressed(ex1);
    throw ex2;
} catch (IllegalArgumentException iae) {
    // handle illegal argument...
    ... iae.getSuppressed() ... // get hold of the suppressed exceptions
}
🌐
BeginnersBook
beginnersbook.com › 2013 › 04 › difference-between-throw-and-throws-in-java
Difference between throw and throws in java
Try to go through the separate articles of throw keyword and throws clause and then go through the differences, you will be able to understand better then. Thanks! ... By using Throw keyword in java you cannot throw more than one exception but using throws you can declare multiple exceptions.
Top answer
1 of 7
4

Java's approach to exceptions is to make method caller aware of failure conditions and thus be forced to handle them or acknowledge the fact that the exception isn't handled via a repeated throws statement on the caller's method. Or put another way, knowing what exceptions are thrown is part of method's signature and thus the explicit throws statement.

For failures conditions that are not expected to occur in normal course of operation, there are two special kinds of exceptions: RuntimeException and Error. Subclasses of these exception do not need to be explicitly declared in a throws clause or caught by the caller.

It would also be worth noting that using "throws Exception" is sloppy programming in production code as it doesn't tell the caller of the method anything about the actual failure cases. The only time I would consider using generic "throws Exception" declaration as opposed to enumerating actual exception types is for cases like unit tests where explicit declaration of failure cases serves no purpose.

2 of 7
3

Although the other answers are right-on, I think they missed the purpose in the way you were asking it.

The throws statement is how you create an exception stack trace. There isn't much magic in java--it's not some underlying system mystery that creates an exception, it is simply a "Throw" statement, and therefore the last few entries in any stack trace will probably be throw.

It's not JUST the last one because in many cases exception handling consists of something like this:

try {
     do something that might cause an exception
catch(ExpectedException e) {
     throw new DifferetnException(e);
}

This lets you change what type of exception it was or add a better textual description or even handle some of the exceptions while re-throwing the others.

Because of this it is often the last few levels (and maybe some in-between) that are caused by the "Throw" statement.

🌐
Medium
medium.com › @AlexanderObregon › java-exception-handling-throws-vs-try-catch-94b0abe1080d
Java Exception Handling — Throws vs. Try-Catch
March 17, 2024 - Here are some key practices to consider when handling exceptions in Java, aiming for clarity, efficiency, and maintainability in your code. When catching exceptions, specificity is key. Aim to catch the most specific exception types related to the operations you’re performing. This approach allows you to handle each exception in the most appropriate manner, providing clear and useful feedback for each distinct error condition. Catching overly broad exceptions, such as Exception or Throwable, can obscure the true nature of an error.
🌐
DataCamp
datacamp.com › doc › java › throws
throws Keyword in Java: Usage & Examples
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming ... The throws keyword in Java is used in method declarations to specify that the method can throw one or more exceptions.