What does "Throws" do and how is it helpful? [duplicate] - java

This question already has answers here:
The throws keyword for exceptions in Java
(4 answers)
Closed 9 years ago.
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 programs using merely a try-catch statement in my methods and it has worked just fine - surely it is these try-catch statements which manage exceptions, right?

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.

Higher up yeah, some method will have to catch the exception that gets thrown. Just like you said, it is the try-catch blocks that manage them.
There is one exception though, and that is the RuntimeException, for which you do not need to declare the throws exception part. RuntimeException(and all of its subclasses) are called unchecked exceptions, after which you usually can not recover.

Throws is a mechanism to throw the exception to the calling method. This is generally used to throw the exception to a level where it can be handled.
A practical example is a gui based application with some backend logic. If there is a problem in the backend, you may want to show a proper message to the user. So from your backend you can throw the exception upto your UI classes and then can display a message accordingly.

Java programs throw exception whenever it is occured.However,there will be times when you want to manually throw exception,for this throws keyword is used.
For example:
class Abc {
public static void main(String args[]) throws IOException{
}}

Related

How can you add use a method that throws an exception without using try/catch in java? [duplicate]

This question already has answers here:
Checked vs Unchecked exception
(7 answers)
Closed 1 year ago.
Sometimes when the JDK declares a method, e.g. Integer.parseInt(String s) it throws a NumberFormatException, yet when the method is called you do not need a try and catch, how can I do this in my own code?
It is little unclear what exactly you are asking about - unchecked exceptions or how to avoiding try-catch-finalize blocks.
Unchecked Exceptions
If you are interested in how a method can throw exception, without declaring throwing it (right before body), then beware, that Java programming language does not require methods to catch or to specify unchecked exceptions ("RuntimeException", "Error", and their subclasses).
In contrast, you always have to handle (or declare to throw) all the other types of exceptions.
Avoiding try-catch-finalize
If, however, you're questioning how to avoid try-catch-finalize blocks, then you may throw an exception to the caller, by declaring your method throwing it, as:
[access-modifier] return-type methodName() throws Exception {
...
};
Use the "throws" clause after method declaration.
Eg: public static void main(String[] args) throws IOException {
}
There are basically two kinds of exceptions. Checked and unckecked in Java. All exceptions derived from RuntimeException are unckecked and you don't have to catch these.
So if you create an own exception which extends RuntimeException you don't have to catch it. Also check the already existing ones as they often already fit your needs. Like IllegalStateException or IllegalArgumentException.
1)To create your own exceptions in Java, you need to extend the
class you want to create from the Exception class in Java. 2)Then,
you can throw your own exceptions by using the throw keyword where
you want to write the error you want to show by override its
constructor or the getMessage method from the Exception class in the
class you created. 3)If you don't want your own exceptions to be try
and catch, you need to extend it from the RuntimeException class.
This exceptions that don't need try_catch are extend from RuntimeException insted of Exception class.
You can create your own RuntimeException like this:
public class CustomException extends RuntimeException {
public CustomException(String msg) {
super(msg);
}
}
Here I leave you a link with more information about diferent exceptions and how to handle them:
https://howtodoinjava.com/java/exception-handling/checked-vs-unchecked-exceptions-in-java/

Need a better explanation for try/catch/throw/throws exception handing in Java

I am a little unsure about the difference between the try/catch, throw and throws in Java and every website seems to have an inhuman way of explaining it, I have tried the Oracle website but I just could not understand their explanation, is this correct?
Try/catch
With try catch, I want to try a piece of code and if something goes wrong do this.
Throw
With throw, I am throwing an error because I want to?
So if I wanted to validate a users age, say all people over 20 and the user does not meet the requirements, I would throw an error?
Throws
With Throws I am throwing an error but something else handles the exception? Would this be another method/class?
Try / Catch
try
{
// try to do some actions
}
catch(SomeExceptionType exception)
{
// if the above actions throw a SomeExceptionType, do these actions
}
Throw
Correct. We're explicitly throwing an exception. You may do this if, for example, the caller of a method has violated your method's contract. Perhaps an argument cannot be negative.
In this situation, the best way to deal with this is to throw an exception which stops what we're doing and allows callers further up the stack to deal with the problem:
/** Do a thing. myInt must be positive */
void someMethod(Integer myInt)
{
if (myInt < 0)
{
throw new IllegalArgumentException("Can't be negative");
}
// do something
}
void myCaller()
{
someMethod( 1); // won't throw
someMethod(-1); // will throw
}
Throws
throws is used as a keyword when dealing with checked exceptions. It's a way of letting callers know what checked exceptions they can expect they may have to deal with.
Those methods can decide to deal with the problem (i.e. a try-catch) or can themselves declare the same exception type to be thrown to propagate the exception up to their caller (and so on and so on)
You forget a important point : in Java all exceptions are not handled by the compiler in the same way.
The compiler ensures only that the checked exceptions be handled.
These exceptions don't inherit from RuntimeException but from Exception (directly or indirectly).
So whatever you throw in your code or a method of a third class declares throwing a checked exception, you have to explicitly handle it.
And there you have two ways :
catching the exception
letting the exception be propagated to the caller
try/catch addresses the first way while specifying the throws modifier in the method declaration addresses the second.
For no RunTimeExceptions, you don't have this constraint as the compiler doesn't force you to handle it. You may handle them if you want to.

What is the point in throws clause?

I understand the point of checked exceptions: to remind the developer of errors that you need to be aware of. I also understand the point of not handling some exceptions if you cannot recover from them. But why is it that, should you decide not to handle a checked error, you have to include a throws statement. If you run this code, you get a runtime error, and should you comment out the throws statement (and add a { ), you get a compile time error. This seems pointless to throw the error out of main() if it still interrupts the program.
import java.io.IOException;
public class Blah {
public static void main(String[] args)
throws IOException {
throw new IOException();
}
}
The throws clause says that a method is allowed to throw certain exceptions. It sets out the contract that the method has with its callers, to let them know which checked exceptions it can throw and thus which exceptions the callers should be prepared to handle, but the called method doesn't have to throw them every time, or at all.
The point of being able to "duck" an exception by adding it to the methods throws clause is just the flexibility when creating code that someone else is going to use.. maybe your code gets the exception, but you would rather for the caller of your method to handle it instead of handling the exception yourself, allowing the calling developer to know what happened instead of just re-throwing the exception or returning a null value.
I understand the point of checked exceptions: to remind the developer of errors that you need to be aware of.
In fact, it is stronger than that. The point is to force the developer (you) to do something about the errors at some point in the application. You can do one of two things:
You can catch and (hopefully) handle the exception in the same method body that it was thrown.
You can add the exception to the throws list of the method ... so that it propagates to method's caller. That puts the initial responsibility for handling the exception onto the caller code.
In this (general) context, the point of throws is clear. If the language didn't have throws declarations, then Java's checked exceptions design wouldn't work1.
As far as the Java Language Spec is concerned, these rules apply equally to all Java methods, including the main method. So you have to put the "pointless" throws IOException on your main. But is it really pointless? I would argue no. Consider the following:
If you allow an exception to propagate out of your application's entry point main, what happens is that the user sees an ugly stacktrace. As far as he / she is concerned, your application has "crashed".
Isn't it better to be told by the Java compiler that your main method will "crash" if an IOException occurs?
Suppose you have two classes in your application which both have a main method. Should both of them be allowed to propagate checked exceptions without declaring them?
What about the case where an application's codebase includes a specific call to a main method. Wouldn't it be better to treat such a call just like other calls ... which depends on the main method declaring the checked exceptions in a throws clause?
As you can see, there are good reasons for wanting the main method to follow the same exception rules as other methods.
1 - Either you'd have to catch checked exceptions in the same method they were thrown and library methods couldn't throw checked exceptions, or you'd need to do a global analysis of each application at load time to see if checked exceptions are caught.
If another program uses the method it needs to be able to catch and handle it

Is it redundant to throw specific exception in Java's method?

Consider the following code snippet.
public static void main(String [] args) throws IOException
{
....
}
My assumption tells me that: Any exception be it arrayOutOfBoundsException or IOException, the program will get terminated since there is no catching of the exception (and the exception thrown is not general). However I do see people throws specific exception at the method signature.
My question: Is it redundant for doing this? (since any exception will cause the program to terminate)
If it is not redundant, what is the reason people do it do this way?
What catches the exception thrown by main method?
the program will get terminated since there is no catching of the exception
It may seem that way because the main method is where your program starts. But actually, the Java Virtual Machine (JVM) calls the main method and therefore technically it catches and handles any exception thrown by it.
The handling done by JVM is merely to print the stack trace of the exception in the error stream, then terminate your program*. Which is why you see that stack trace in the console (unless the error stream was redirected elsewhere, like a file) before the program terminates.
* If no other programs (such as live non-daemon threads) are running in the JVM, it will also terminate itself.
Why should it be declared?
However I do see people throws specific exception at the method signature.
Is it redundant for doing this? (since any exception will cause the program to terminate)
First, I should clarify that by writing throws, the programmer is not throwing the exception. The programmer is merely declaring that this exception may be thrown by the method, and a caller of the method must handle it in some way.
To take your example:
public static void main(String [] args) throws IOException
This is most likely added by the programmer because his program calls some method from another class that also declares this. Some common examples are:
public FileWriter(String fileName) throws IOException // a constructor can also throw exceptions
FileWriter.write(int c) throws IOException
The designer of this FileWriter class has made it mandatory for its user (the programmer) to handle the IOException. This is called a checked exception.
The two types of exceptions
A checked exception tells the user that during the program run, the scenario causing this exception is likely to happen even though it normally shouldn't (because we don't live in an ideal world). This suggests an environmental error and such an exception can be thrown even in the best program.
The other type of an exception is the unchecked exception. The reason why you don't declare NullPointerException (an unchecked exception) using throws is because the scenario causing it is not expected to happen during a normal program run. If it happens, this suggests a programming error and a badly written program.
How do you handle an exception?
There are two ways to handle the exception received in a method.
First is the way the programmer has done in your example. Simply throw that exception back to the caller.
Second is to use a try-catch block to handle it internally:
public static void main (String [] args) // no need to declare "throws IOException"
{
try {
/* some code here that may throw IOException */
} catch (IOException ioe) {
System.err.println("Uhhhh something went wrong!");
// or some logging can happen
ioe.printStackTrace();
System.exit(-6); // a custom error signal can be sent in termination
}
}
But again, why?
If it is not redundant, what is the reason people do it do this way?
They do it because Java forces checked exceptions to be handled explicitly, while unchecked exceptions can be left unhandled.
As I have already explained the two ways an exception can be handled, it should be noted that programmers may pick one way over another depending on the situation. For some methods it may make more sense to throw a caught exception to the caller, while for others it would make more sense to handle the caught exception internally.
Then there are those lazy programmers who just declares every checked exception with throws.
Notes
Both checked and unchecked exceptions can be handled using either of the two ways above. Unchecked exceptions give you the third choice of not handling it, which in turn gives the caller the choice of handling or not handling it.
If you declare an unchecked exception using throws, it will become a checked exception to the caller of your method.
You can also mix and match both ways. For example, you may handle a checked exception internally at any point in the method, even if it is declared to be thrown in the method signature. The throws declaration will only take effect where the checked exception is not handled internally.
The main method of a class can be called like any other regular static method in your program, just by passing in a String array of arguments. It is only special in the sense that the JVM calls this method when the class is started as a Java program. When you manually call the main method, you have to handle the checked exceptions that may be thrown.
If some code in main throws a checked exception (like IOException), you have to declare it in throws. The main method is just like a normal method in that regard (in fact, it's just like a normal method in all regards, except that it's also an entry point for the program).

Java what is the benefit of Throwing RuntimeException

What is the benefit of declaring (Unchecked Exception)throws exception along method signature b/c it does not force caller to keep in try catch block.
public void testRuntimeEx()throws RuntimeException{
if(1==1){throw new RuntimeException()}
}
//Caller method
public void testCaller(){
// not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature
testRuntimeEx();
}
It still serves as documentation, especially if you do not use a generic RuntimeException, but something more specific like IllegalArgumentException or UnsupportedOperationException or IndexOutOfBoundsException and also add some JavaDoc as to when that would happen.
In your example code snippet, it is pretty meaningless, though.
This declaring is a signal for developer who uses this code, that it throws RuntimeException.
But it doesn't smell good.
P.S. Code you posted will not compile:
throw RuntimeException
This is not correct throwing.
The benefit is that typically caller does not have anything to do with the exception. It catches it, wraps with other exception and throws again. Or, alternatively, declares the exception using throws keyword and becomes transparent for this type if exception.
I'd say that the described situation is typical for applications where we usually write business code and have one centralized place that handles all exceptions. It is not correct for APIs. For example if you are using library that implements SSH you are expecting it to throw IOException (or even more specialize exception) when something is going wrong.
if you throw custom unchecked exception it becomes more meaningfull rather catching system exception and unchecked exception does not force to catch too.

Categories