Domanda

I noticed that both of these, for example, are working:

public void func(int a) throws IllegalArgumentException {
    if(a < 0) 
        throw new IllegalArgumentException("a should be greater than 0.");
}

public void func(int a) {
    if(a < 0) 
        throw new IllegalArgumentException("a should be greater than 0.");
}

It makes me to ask:

When should I announce throws anException, and when not, and just throw it without declare about it?

È stato utile?

Soluzione

Checked exceptions must be always written in the method signature that it throws.

If the exception extend RuntimeException, you don't have to write throws in the method name, but it's highly recommended since it's clearer and it'll be mentioned in the documentation of the method.

/**
 * @throws This won't appear if you don't write `throws` and this might
 * mislead the programmer.
 */
public void func(int a) throws IllegalArgumentException {
    if(a < 0) 
        throw new IllegalArgumentException("a should be greater than 0.");
}

Altri suggerimenti

The beauty with Throws is that the Exception converts into Checked Exception thus every time any developer will try to use the first approach he will be warned to place a try-catch block before calling the method which has Throws in its Signature.

From the JLS section 11.2:

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor. For each checked exception which is a possible result, the throws clause for the method (§8.4.6) or constructor (§8.8.5) must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

so briefly, you need the throws statement if an exception is checked. If you have an Exception, and it's not a subclass of RuntimeException, then it's checked.

IllegalArgumentException is a subclass of RuntimeException, and so it's unchecked, and you shouldn't need to declare it in a throws statement. This is true of most exceptions like this (IllegalArgumentException, NullPtrException etc.) since you can't reasonably be expected to handle these easily.

When your exception is checked you are obliged by the compiler either to catch the exception or announce a throws declaration.
Check this post for a comparison of checked vs unchecked exceptions.

This is because IllegalArgumentException extends RuntimeException. You can't leave the throws clause in below like case.

public void func(int a) {
    if(a == 0) 
        throw new Exception("a should be greater than 0.");
}

There have been many technical answers that are JLS Section 1.2, Checked exceptions etc which explains the use of it.
But your question

When should I announce throws an Exception, and when not, and just throw it without declare about it?

If your code is generating some explicit exception and throwing it, then you should always add throws clause and you should generate documentation by just writing /** above the function which will generate the documentation tags for you. This will help all the other users who use your library or functions that the certain function or constructor is bound to throw an exception if some invalid arguments or some values have not been initialized prior to call of this function.

Example,

/**
 * 
 * @param filePath File path for the file which is to be read   
 * @throws FileNotFoundException In case there exists no file at specified location
 * @throws IllegalArgumentException In case when supplied string is null or whitespace
 */
public static void ReadFile(String filePath) throws FileNotFoundException, IllegalArgumentException 
{
    if(filePath == null || filePath == "")
     throw new IllegalArgumentException(" Invalid arguments are supplied ");
    File fil = new File(filePath);
    if(!fil.exists()|| fil.isDirectory())
        throw new FileNotFoundException(" No file exist at specified location " + filePath);
    //..... Rest of code to read file and perform necessay operation
}

These documentation tags and throws are moreover to make the programmer life easy who will reuse your code and will know in advance that IllegalArgumentException, FileNotFoundException will be thrown if function is invoked with wrong parameter or file is not available at specified location.

So if you want that your code and functions are self explanatory and provides all necessary cases what exceptions are thrown then add the following clauses otherwise it is your choice.
Remember, if after 30 days if you yourself are using (I am sure you are going to re-use it near future) those function then it will be much more helpful and you will exactly know just by those clauses what I did in that function.

While you need to declare the checked exceptions, Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor .. from - http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top