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
ArithmeticExceptionof division by zero occurs or anArrayIndexOutOfBoundsExceptionoccurs, 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
StackOverflowErroroccurs, our program cannot do much, such as increase the size of program's function calling stack. Or if anOutOfMemoryErroroccurs, 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
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
ArithmeticExceptionof division by zero occurs or anArrayIndexOutOfBoundsExceptionoccurs, 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
StackOverflowErroroccurs, our program cannot do much, such as increase the size of program's function calling stack. Or if anOutOfMemoryErroroccurs, 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
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.
java - What does "Throws" do and how is it helpful? - Stack Overflow
java - Why shouldn't a method throw multiple types of checked exceptions? - Software Engineering Stack Exchange
java - Is "throws Throwable" good practice - Stack Overflow
exception - How to avoid many try catch blocks in java - Stack Overflow
Can a method use both throw and throws?
Can we use throw without throws?
Videos
Hey,
so what is the use of the keyword „throws“? I found in several sources something like this:
„Throws keyword can be placed in the method declaration. It denotes which exceptions can be thrown from this method.“
But why cant i just make a comment and say: // this and this exception might be thrown
I dont really know why this was implemented? There must be something i clearly didnt understand
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.
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.
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.
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.
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
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.
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.
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.
If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.
Typically, if you are not going to do anything with the exception, you should not catch it.
The most dangerous thing you can do is catch an exception and not do anything with it.
A good discussion of when it is appropriate to throw exceptions is here
When to throw an exception?
You only need to include a throws clause on a method if the method throws a checked exception. If the method throws a runtime exception then there is no need to do so.
See here for some background on checked vs unchecked exceptions: http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
If the method catches the exception and deals with it internally (as in your second example) then there is no need to include a throws clause.
Is it good practice to ALWAYS write "throws" in the method signature to show which exceptions could be raised? Should this be done everytime?
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.)
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
NotFoundExceptionthe 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.
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).
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
}
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.
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.