This question already has answers here:
throw new Exception vs Catch block
(5 answers)
Understanding checked vs unchecked exceptions in Java
(21 answers)
Closed 9 years ago.
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?
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.");
}
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
Related
I have been working with a library and I notice the following construct.
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
I am having difficulty in identifying if it is an anonymous class as I don't see it using the interface or concrete class.
Or is it a just a normal method that does a throws IOException.
I am coming from a different programming background and looks kind of strange for me.
Are you forced to use throws ?
If you are asking about the presence of throws IOException, you must declare it using the throws keyword, because it is a checked exception.
So basically
String run (String url) throws IOException { ... }
^ ^ ^ ^
method method param type marks checked ^
return type name and name exceptions the method body
method may throw
Basically, checked exception in Java is any subclass of Throwable which does not inherit from RuntimeException or Error. Whenever your code throws a checked exception, the Java compiler forces you to either catch it or declare it using the throws keyword.
Checked exceptions allow you to verify at compile time that you are either handling exceptions or declaring them to be thrown: When you call a method like run(), the compiler will warn you that you must do something about it (catch or declare). For some explanation why Java enforces this, see e.g. this question on SO.
The article linked above explains what is the semantical difference between checked (e.g. NullPointerException) and unchecked exceptions (e.g. IOException)
Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time
Checked exceptions represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
It is a method.
The signature of the method is String run(String url) throws IOException. It means that the method name is run; that the method take a String as argument; return another String and may throw an IOException.
"Given that FileInputStream’s constructor throws FileNotFoundException, which is a subclass of
Exception, write the header for a public method named process that takes a String parameter
and returns nothing, and whose body instantiates a FileInputStream object and does not contain
a try-catch statement."
I know it's a too-simple question but I want to make sure I'm not messing up in a dumb way. Also, not sure whether to use FileNotFoundException or just Exception or IO, etc.
public process(String file) throws FileNotFoundException {
FileInputStream file = new FileInputStream("stuff.txt");
}
What you have for the throws clause is good. Throwing IOException would not be terrible, but it's better to be specific. Calling code can still treat it as an IOException.
Generally you shouldn't throw Exception except for special cases (Junit methods and similar situations where everything thrown will get caught by an exception handler), because it forces everything that calls it into the position of either handling Exception (where it may not be the appropriate place to do it, it is better to let most exceptions bubble up to one place where they can get handled uniformly) or also throwing Exception, which then puts other calling methods in the same position.
Your method declaration is not valid because there's no return type. Methods that don't return anything are declared with a return type of void.
Using the same name for a method parameter as for a local variable will not work, you should make those different. The constructor call should take the method parameter as an argument (instead of hard-coding a string literal). (+1 to geceo's answer for pointing that one out, I had missed that one.)
As a suggestion, your code would be clearer if it used names that reflected the contents of the variables. Calling a FileInputStream file is not clear, it would be better to call it inputStream. Calling a String file is not clear, it would be better to call it filename.
What you have is fine (except you're missing the void return type).
Always throw (and catch) the narrowest specification of Exception you can (in this case FileNotFoundException).
As spotted by Nathan, you forgot to declare that process returns nothing, that is, you forgot the void keyword.
There's another problem with your parameter String file ("duplicate local variable file"). You should rename it String filename and pass it to the constructor of FileInputStream:
public void process(String filename) throws FileNotFoundException {
FileInputStream file = new FileInputStream(filename);
}
About the general topic, you always have to make a choice when you call a method that throws exception(s):
You can use a try/catch block and deal with the error in your calling method (log them, for example);
or
You can propagate the exception using the throws keyword in your method declaration.
So what you're doing here is the second possibility.
Also add void as the return type. Rest is fine.
public void process(String file) throws FileNotFoundException {
FileInputStream file = new FileInputStream("stuff.txt");
}
You can do few things to make your method better by buying insurance against accidental misuse:
public void process(final String file) throws FileNotFoundException {
final FileInputStream inputStream = new FileInputStream("stuff.txt");
//invoke operations on inputStream object
//After 100 lines of code
inputStream = new FileInputStream("foo.txt"); // compile error
}
Observe the final keyword next to parameter passed to method and FileInputStream object reference.
I have a bit of confusion in the following snippet.
try {
public static void showMyName(String str) throws IOException
{
if(str.equals("What is your Name?"))
throw new IOException;
}
}catch(IOException e)
{
System.out.println ("Exception occurs , catch block called")
}
Now, my question is what is difference between throws IOException && throw new IOException
Why don't we require to use catch , finally block for throws IOException ?
How does throws is handle the exception. ?
When an Exception is generated, there are two ways to deal with it.
Handle the Exception - this uses catch block
Declare the Exception - this uses throws block
So, dealing with an already generated exception is done by catch or throws.
On the other hand, throw is used while an Exception is "generated".
Typically, the throw keyword is used when you're instantiating an Exception object or while cascading an already generated exception to the caller.
For example,
public void doSomething(String name) throws SomeException { // Exception declared
if( name == null ){ // cause of the exception
throw new SomeException(); // actual NEW exception object instantiated and thrown
}
// Do something here
.
.
.
}
In the calling method,
public static void main(String[] args) throws SomeException{ // Need to declare exception because you're "throwing" it from inside this method.
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
throw e;// throw the exception object generated in doSomething()
}
}
Alternately, you can "handle" the exception in the catch block:
public static void main(String[] args) { // No need to declare exception
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
System.out.println("Exception occurred " + e.getMessage()); // Handle the exception by notifying the user.
}
}
Hope this helps.
Addendum - Exception Handling glossary
try - used for invoking code that can potentially cause exceptions or with resources such as Files/Streams/Network/Database connections.
catch - used immediately after a try block to "handle" or "throw" exceptions. Optional if finally is used.
finally - used immediately after a try or catch block. Optional. Used for executing code that "must" be executed. Code within a finally block always gets executed - even if the try or catch has a return statement.
throw - used to "push" or "cascade" exceptions through the calling methods. Always used inside a method.
throws - used to "declare" that a method will be throwing an exception if something goes wrong. Always used as part of method signature.
Addional Reading
Here's an elaborate article to help you understand the try-catch-finally semantics in java.
Update
To answer your other question,
Why don't we require to use catch , finally block for throws
IOException ?
Think of catch and throws as mutually exclusive constructs. (This is not always true, but for your understanding, it's good to start with this thought.)
You declare a method that it throws IOException. This piece of code is written at a point where you declare the method. And, syntactically, you cannot place a method declaration inside a try block.
How does throws is handle the exception. ?
Like I mentioned before, catch and finally are used during exception handling. throws is just used to cascade the exception back to the caller.
throw new IOException means that you encountered some error condition and decided to break the flow of the program by throwing an exception.
If that exception is a checked exception (i.e. not Error or RuntimeException), you must either catch that exception in a catch block, or declare in the method's signature that the method is expected to throw that exception (or a super-class of that exception). That's what the throws IOException means.
You are pretty much right on. Except for one thing I'll mention in a bit.
throws is as much a part of the method API as the name and the parameters. Clients know if they call that method, they need to handle that exception--by simply throwing it also or by catching it and handling it (which may in fact entail the throwing of another exception wrapping the original). throws is addressed at compile time.
throw is the actual act of letting the runtime know something bad happened--that the exceptional condition we were worried about has in fact taken place. So it needs to be dealt with at runtime.
But you weren't quite right when you said, "Throws in method signature should always appear if there exist a throw statement in the method." That is often true but not always. I could also call another method that throws an exception within my method, and if I don't catch it, my method needs to throw it. In that case, there is no explicit throw of the same exception by me.
The final point is that you only need to declare an exception in throws when the exception is a checked exception--meaning it is from the other side of the Exception class hierarchy from RuntimeException. Common checked exceptions are IOException and SQLException. Checked exceptions must be listed in the throws part of the method signature if you don't handle them yourself. Anything subclassing RuntimeException--like NoSuchElementException in your example and also the hated NullPointerException--is an unchecked exception and doesn't have to be caught or thrown or anything.
Typically, you use checked exceptions for recoverable problems (where the client knows what can happen and can gracefully handle the problem and move on) and unchecked exceptions for catastrophic problems (like can't connect to the database).
If you can get past all the AOP stuff, this is a great discussion of how you use checked and unchecked exceptions effectively.
The first biggest difference is throw can throw exception like you throw stone in river,
and throws state that this method have chances to throw exception but may not also... and thats why throws dont need try catch because it state already that it gona throw some kind of exception.
throws keyword means that this method will throw any Exception that will have to be handled in a higher level.
public static void showMyName(String str) throws IOException
If another method call this method, it has to catch this exception or throw it one more time (by typing throws in its signature).
Catch the exception or keep throwing it, depends on your business logic.
So I have a pretty big java application that I wrote a year ago and I'm trying to understand it again. I'm looking at a method in the code where there is an obvious risk of getting NoSuchElementException: I'm calling .next() on a scanner variable that has been constructed with an arbitrary string. The only thing the method is declared to throw are custom made subclasses of Exception. The risky command isn't written in a catch-block either. The code compiles and works fine and when I use my gui in such a fashion that it should throw a NoSuchElementException nothing happens :O
As a test I wrote a catch-block into the code, compiled it, ran the gui and made it throw NoSuchElementException again and the application successfully caught the exception and acted accordingly. How is it that I can compile the code without specifying the this exception may be thrown? If it's any use at all, here is the code without the catch-block:
public static Expression interpret(final Scanner scanner)
throws
InvalidPosition,
NoSuchSpreadsheet,
IllegalStartOfExpression,
InvalidExpression,
FalseSyntax,
InvalidRange {
String keyword = null;
try {
keyword = scanner.next();
} catch (NoSuchElementException e) {
throw new IllegalStartOfExpression();
}
switch(keyword) {
case "Get":
Position pos = PositionInterpreter.interpret(scanner.next());
Expression expression = Application.instance.get(pos);
if (expression instanceof Text) {
System.out.println("Failure");
} else { System.out.println("Success"); }
return new Text(expression.toString());
case "Int":
return new Int(
scanner.nextInt());
As you can see, the method simply assumes that there is more than one word in the scanner after checking if there is at least the one. How am I getting away with compiling this?
It is be cause NoSuchElementException is unchecked exception, which means that it "is-a" RuntimeException which does not force you to catch.
The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by programmers. See ref for a description of the exception class hierarchy and some of the exception classes defined by the Java API and Java virtual machine.
Runtime exceptions serve the same purpose as checked exceptions; to communicate exceptional conditions (unexpected failures, etc) to the user.
checked exception forces the caller of a method to handle that exception, even if they do not know how to handle it. Often times, developers will end up catching the checked exception, only to re-throw it (or another exception). Hence the Runtime exceptions
Here is the exception hierarchy
As the question has already been answered, I'd like to point on that this is very poor design and not the intended usage of the Scanner class:
try {
keyword = scanner.next();
} catch (NoSuchElementException e) {
throw new IllegalStartOfExpression();
}
What you should really be doing is ask the scanner whether there is any input, and only then retrieving it, like so:
if(scanner.hasNext()) {
keyword = scanner.next();
}
else {
throw new IllegalStartOfExpression();
}
The same applies to the line which is causing your problem:
if(scanner.hasNextInt()) {
return new Integer(scanner.nextInt());
}
java.util.NoSuchElementException is a subclass of java.lang.RuntimeException. RuntimeExceptions don't have to be handled. From the Java API documentation:
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked 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 and propagate outside the method or constructor boundary.
I'm reading exception handling in the book "A programmer guide to Java SCJP certificate". The author wrote that :
If a checked exception is thrown in a method, it must be handled in one of three ways:
1.By using a try block and catching the exception in a handler and dealing with it
2.By using a try block and catching the exception in a handler, but throwing
another exception that is either unchecked or declared in its throws clause
3.By explicitly allowing propagation of the exception to its caller by declaring it
in the throws clause of its method header
I understood clearly the first and third, but the second made me a lot of confused. My concerns are that :
-It's still alright even if I don't throw any other unchecked exceptions, so why do we have to throw another exception at here?
-Why do we have to re-declare the exception that we have caught, in throws clause? I think it's over by the handler.
Thanks to everyone.
The book just list three allowed options.
-It's still alright even if I don't throw any other unchecked exceptions,
so why do we have to throw another
exception at here?
You might want to throw another more descriptive exception, for example adding more info.
-Why do we have to re-declare the exception that we have caught, in
throws clause? I think it's over by
the handler.
You don't have to re-declare. But if the new exception you are throwing is checked, then you must declare it in the throws clause. In fact the exception you just caught doesn't need to be declared even if checked.
You may want to do this to catch a checked exception and throw another checked exception of a different kind. Perhaps you want to throw your own exception rather than a different one.
public void doSomething() throws MyCheckedException {
try {
doSomethingThatThrowsSpecificCheckedException();
} catch(SpecificCheckedException e) {
throw new MyCheckedException();
}
}
Or you can throw an unchecked exception (something that is or extends RuntimeException).
public void doSomething() {
try {
doSomethingThatThrowsSpecificCheckedException();
} catch(SpecificCheckedException e) {
throw new RuntimeException();
}
}
First of all, you should declare in the throw clause the exception that you throw, not the one you caught, assuming you are throwing a checked exception.
Second, you don't have to do that. It is just one of the three options.
Why would you do that? Usually this is done between the application layers. For example, Hibernate catches SQLExceptions and rethrows them as unchecked HibernateException, so that code that calls Hibernate methods doesn't have to be polluted with the try/catches for SQLExceptions. Another option is to translate a low-level exception into some business logic exception that can be handled up the stack. This allows for the better isolation of the business logic from the low level implementation details.
Great question, and one which good java programmers should get their head around.
It's all about adhering to the method signature that defines the method's contract with its caller, and which includes what exceptions you are going to throw.
Option 1 is dealing with the exception
Option 2 is not dealing with the exception, but keeping the same contract
Option 3 is not dealing with the exception and changing your contract
A implementation of the pattern in option 2 would be:
public interface Server {
public void useServer() throws ServerException;
}
public class ExplodingClient {
private Server server = new ServerImpl();
public void doIt() throws ClientException {
try {
server.useServer();
} catch (ServerException e) {
// Our contract doesn't allow throwing ServerException,
// so wrap it in an exception we are allowed by contract to throw
throw new ClientException(e);
}
}
}
public class SilentClient {
private Server server = new ServerImpl();
public void doIt() {
try {
server.useServer();
} catch (ServerException e) {
// Our contract doesn't allow throwing any Exceptions,
// so wrap it in a RuntimeException
throw new RuntimeException(e);
}
}
}
By using a try block and catching the
exception in a handler, but throwing
another exception that is either
unchecked or declared in its throws
clause.
Handling the exception in Java can be done in two ways :
Wrapping it in try-catch-finally block.
Declaring the method to throw ( using throws) the exception to the caller of method to handle.
-It's still alright even if I don't throw any other unchecked exceptions,
so why do we have to throw another
exception at here?
Throwing another exception means describing more about it. Also, to let the caller of the method know that this particular exception was generated.
-Why do we have to re-declare the exception that we have caught, in
throws clause? I think it's over by
the handler.
Redeclaring exception that you just caught in the catch block is to make the caller of this method alert that this method could throw a particluar exception. So be prepare to handle it.
You must go over this Jon Skeet's post : Sheer Evil: Rethrowing exceptions in Java
Remember, you are never forced to handle the unchecked exceptions, compiler forces you to just catch the checked one.