Max Yankov
Max Yankov

Reputation: 13287

What's the purpose of the 'throws' statement in Java?

I'm just learning java, but it seems that in the end most of the methods in the beginning of the call stack will just have declarations 'throws Exception'. What's the good thing about this statement that I'm missing that makes it useful?

One more example. After writing some code, I decided to refactor one of my classes a bit, using classes from other java libraries; as a result, not only half of the methods of this class gained another 5 exceptions in their declarations, but about half of all my other code, too – until I decided I'd better just write 'throws exception' and don't care about. May be I just use exceptions wrong?

Important edit

My question wasn't about what that statement does – it is pretty obvious from documentation. I was actually wondering why language designers decided to make this statement necessary.

Upvotes: 2

Views: 7310

Answers (7)

Max Yankov
Max Yankov

Reputation: 13287

After a lot of reading about exceptions and best practices, I realized that I made a mistake, using Exception class for handling programming errors – which I check for in literally every method – where as I should've used RuntimeException, which is not required to be checked. After refactoring my code I got 'throws' statements only in places necessary, and now it is neat and clean.

Upvotes: 2

Heisenbug
Heisenbug

Reputation: 39164

Throws raise an exception. An exception will be passed backward to the function into the stack until it is caught by a catch block, that can handle it.

When throw keyword is put in a method declaration it indicates that a call to that method could generate an exception. For example:

public void methodFoo (int val) throws IllegalArgumentException  {
    if (val <0) throw new IllegalArgumentExecption();
}

means that the methodFoo can raise an exception of the type IllegalArgumentException. When you call such a method you typically use the following try/catch block statement:

try{
   methodFoo(int param);

}catch (IllegalArgumentException e){
       //if any method call inside methodFoo will raise such exception the execution flow of the program will be interrupted and the execution restart from the first catch block that intercept that execption
}

The "good" of this approach is that, with such feature, you are not forced to check the return value of a method to be sure that your method call succeded. in C language you usually do something like:

int ret = methodFoo();

if (ret == null){
     //error
}

Upvotes: -1

phlogratos
phlogratos

Reputation: 13924

In Java there are Checked Exceptions and Runtime Exceptions.

Checked Exceptions can only occur in Methods that declare them explicitly. Runtime Exceptions can occur anywhere in the code and don't have to be declared. The throws IOException clause declares that in this method there will possibly occur an IOException.

Runtime Exception are those that extend the class RuntimeException. All others are Checked Exceptions.

Exceptions are actually thrown by Statements like throw new IOException(...) inside the method.

Upvotes: 0

Bill K
Bill K

Reputation: 62759

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.

Upvotes: 3

Konstantin Komissarchik
Konstantin Komissarchik

Reputation: 29139

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.

Upvotes: 4

duffymo
duffymo

Reputation: 308733

It indicates to users of the class that an exceptional situation has arisen that they have to deal with. The subject of the throws clause tells the user what those exceptional situations are.

If the exception is a checked exception, the compiler will enforce a try/catch block in the user's code; unchecked exceptions do not require a catch block for handling. In that case the exception will continue to bubble up the call stack until it's either handled or the program is exited.

Upvotes: 2

BZ.
BZ.

Reputation: 1946

It makes you aware of possible problems that may occur and forces you to either deal with them or explicitly say you are not.

Upvotes: 0

Related Questions