Is it necessary to use "throws" whenever we use "throw"? - java

Assuming that the Exception we are throwing is checked, is it compulsory to add throws in a method declaration whenever we use throw inside the method?

Any checked exception (e.g., one which does not extend RuntimeException) that might escape a method needs to be declared in the method signature. For example:
public static void mightThrow(String s) throws NumberFormatException {
// ...
int x = Integer.parseInt(s);
// ...
}
Even though we do not throw any exceptions directly, Integer.parseInt() might throw a checked NumberFormatException. Since we call that method, and we do not catch the potential exception, then our method must also declare the exeception in its throws signature.
This does not necessarily mean that every method that throws (or might throw) a checked exception must declare throws in its signature. If the thrown exception is always caught within that method, it need not be added to the signature. For example:
public static Integer tryParseInteger(final String s) {
try {
return Integer.parseInt(s);
}
catch (NumberFormatException ignored) {
return null;
}
}
In this example, we will always catch any NumberFormatException that might be thrown by Integer.parseInt() and prevent it from bubbling up the stack, so we do not need to declare it in our tryParseInteger() method.
Unchecked exceptions never need to be declared:
public static void unsupported() {
throw new UnsupportedOperationException(
"The specified operation is not supported."
);
}
Here, because UnsupportedOperationException derives from the unchecked RuntimeException, it does not need to be declared.

No, since you may want to throw a exception but handle it in the same place, aka method

The Throws simply let javac know that this method might cause this kind of exception. It is not always necessary. It's useful when you know that a specific method can throw some sort of exception.

Generally speaking, Java is exception-strict, so you have to specific what types of exceptions a method throws. Note that you can use inheritance to simplify your methods' signatures. E.g., you can declare your method as throws IOException, and within its implementation throw any type of IOException you want such as FileNotFoundExeption, InteruptedIOException, etc.
One exception (no pun intended) to this rule are RuntimeExceptions (such as OutOfMemoryError or UnsupportedOperationException) which can be thrown without having to declare them.

Differences:
1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException("not able to open connection").
2) throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method
signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:
private static boolean shutdown() {
throw new UnsupportedOperationException("Not yet implemented");
}
as in below method shutdown should return boolean but having throw in place compiler understand that this method will always throw exception .
3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside method or static initializer block provided sufficient exception handling as shown in example.
static{
try {
throw new Exception("Not able to initialized");
} catch (Exception ex) {
Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
4) throw keyword can also be used to break a switch statement without using break keyword.
int number = 5;
switch(number){
case 1:
throw new RuntimeException("Exception number 1");
case 2:
throw new RuntimeException("Exception number 2");
}

Related

Function's return type can be Exception when it throws Exception

Let's say I have a function
private RuntimeException foo() {
return new RuntimeException();
}
and exception there is not thrown and it can be processed like
throw foo();
or return value can be assigned to a variable
RuntimeException e = foo();
But the function can be changed to
private RuntimeException foo() {
throw new RuntimeException();
}
and it still compiles and can be used like in previous examples or can just be called like foo(); and Exception will be thrown.
But why is it possible to specify RuntimeException as a return type of a method that doesn't return it but throws it instead. Is there any connection between throw and return behavior in this case?
I've noticed that having Exception (or more generally Throwable) return type ensures that it will be thrown/returned in every decision branch like if/else statements. But is there any more practical usage or recommended of this?
Since throw will make the execution of the method stop immediately and control is passed back to the caller, it doesn't matter what your method returns. No matter what type you return, that type will not be returned, because you are throwing an exception (which indicates something wrong happened) on the first line.
The compiler allows this because throwing an exception means something wrong happened, like the arguments are invalid, or the argument is null, and so on. In such error conditions, the compiler does not expect the method to return a value normally. It makes sense because obviously when something wrong happens, the method can't compute whatever it is that it was going to compute.
So the phrase "all code paths must return a value" should really say "all code paths must return a value or throw a Throwable".
There is no relation between what a method returns and what it can throw.
and there are use cases where a method may both return and throw an exception.
consider the following scenario: a method that is called to produce an application-specific exception:
public Exception produceException(User u) {
if (u.id == null) return new UserNotFoundException();
if (u.name == null) return new UserDidNotCompleteRegistrationException();
if (u.email == null) return new UserDidNotVerifyEmailException();
}
now guess what will happen if the argument itself is null? and the method does not even declares a throws clause...
now, regarding having Exception as return value for the sake of ensuring that an exception is returned at every branch is just bad design. return value is not the mechanism to be used for throwing exception. if you surround the entire method body with try-catch you will catch all exceptions from all branches.
why is it possible to specify RuntimeException as a return type of a method that doesn't return it but throws it instead. Is there any connection between throw and return behavior in this case?
It's possible to specify any type as a return type of any method. There is no connection between return and throw behavior.
I've noticed that having Exception (or more generally Throwable) return type ensures that it will be thrown/returned in every decision branch like if/else statements
No, that's not the case. There is no way to "ensure [an Exception] will be thrown in every decision branch". The only thing you can do is to state "this method may throw an Exception by using the throws keyword:
public void mightThrowException() throws Exception {...}
but there's no guarantee that any exception will be thrown at all.
BTW, there are two types of exceptions: checked and unchecked. Unchecked exceptions are subclasses of RuntimeException; those do not need to be declared for your method. Checked exceptions do, so
public void throwsIoException() {
throw new IOException();
}
is illegal because IOException is a checked exception that needs to be declared with throws.
You mixed something up with your example. Because when throwing an exception in a method the return type is not really considered, so instead of declaring the method like in your example. you could also declare it like the following:
public void foo(){
throw new RuntimeException();
}
or:
public MyComplexType foo2(){
throw new RuntimeException();
}
The result is simply the same: An exception is thrown. The calling code just will look differently e.g:
foo(); // throws RuntimeException
myOtherComputation(); // is never reached
or
MyComplexType type = foo2(); // throws RuntimeException
type.doSomething(); // is never reached
This behaviour can be useful when using for example a switch statement in a method but throwing an error when entering the default branch:
public String foo(String string){
switch(string){
case "foo":
return "bar";
case "bar":
return "foo";
default:
throw new UnsupportedOperationException("Unknown string: '" + string + "'!");
}
}

Custom Unchecked Exceptions

Okay guys I've been trying to figure this out for the past day or so. My homework assignment has me creating both Unchecked and Checked Exceptions. The checked exceptions I believe I get basically they must be handled before compiling (With try & catch or throwing it to the next thing that calls it. For unchecked exceptions I don't understand how custom ones work. They are caught at runtime and don't necessarily need to be thrown or encased with try & catch but if they're custom how does the IDE or whatever know what to look for? Example: One of my custom Unchecked files is supposed to trigger if the user adds a pokemon but the party is full, but how do I tell the IDE that that's what needs to happen? My Exception file looks like:
public class PartyIsFullException extends RuntimeException {
public PartyIsFullException() {
super();
}
public PartyIsFullException(String message) {
super(message);
}
}
and then I want to implement it in this method, but idk how to do it. I realize now I can't throw them because the user won't be expecting them and therefore won't try to catch them.
public void addToParty(String name) throws PartyIsFullException {
boolean exists = false;
for (int i = 0; i < 152; i++) {
exists = (name.equals(pokedex[i]));
}
if (exists) {
throw new PokemonAlreadyExistsException();
} else {
if (partyPos < 6) {
party[partyPos] = name;
partyPos++;
} else {
throw new PartyIsFullException();
}
}
}
I realize now I can't throw them because the user won't be expecting them and therefore won't try to catch them.
You can throw them!
In a real project, it should be clearly documented.
/*
* #throws PartyIsFullException if isPartyFull() would return true
*/
public void addToParty(String name) throws PartyIsFullException {...}
Usually an unchecked exception is used for a situation where the client of the method is avoiding the exceptional condition themselves e.g.:
if(theParty.isPartyFull()) {
// tell the user the party is full
// and they can't add more Pokemon
} else {
theParty.addToParty(thePokemon);
}
And thus they shouldn't have to explicitly catch it because they are already handling that circumstance.
If the exception is thrown and there is not a try-catch outside, it will throw all the way up to terminate the thread. (For a small program with just main, this means the program crashes.)
Although you don't know if a certain custom unchecked exception could or not be thrown from a certain method you still can catch it (or it's superclass Exception). Having custom exception against provided by Java could add some useful details specific for your exceptional case (i.e. exception name should be meaningful so that it makes it easier to read your logs).
Custom (unchecked) exception creation and it's content could also be tuned to suit your particular need. E.g. PartyIsFullException constructor could take a Party object and format it's state into a String.
In case you don't need to facilitate your unchecked exception creation/presentation it's OK to go with RuntimeException assuming you provide a descriptive message.

what is the effect that explicits the "throw exception" in the method signature

--the effects of case 1 and 2 are the same, why need to add the exception declaration in method signature?
//case 1
public void doSomething() throws Exception {
//do Something
}
public void Caller() {
try {
doSomething();
} catch (Exception e) {
//handle the exception
}
}
//case 2
public void doSomething() {
//do Something
}
public void Caller() {
try {
doSomething();
} catch (Exception e) {
//handle the exception
}
}
reference:
what is the use of throws Exception
The throws declaration is used to declare which checked exceptions your method throws.
For instance, if I write this code:
public void doSomething() throws SQLException {
}
any code that calls this method must have a try/catch block for SQLException, Exception, or Throwable... or it can have its own throws declaration for one of those 3.
In this case, there is no difference, except that you're alerting the compiler to an exception that you're not going to be throwing.
It's also a bad idea to catch throw "Exception" - in both cases, you want to deal a particular exception that has a particular meaning. When you're catching, the only reason to use a try block is if you expect a particular exception, so you should catch that one. This way, if some unexpected exception comes up, you don't try to handle it the wrong way. (instead, your program fails, and you know there's a condition you have to deal with) When you're throwing, you want to throw a particular exception, either one you make up, or a standard one that has a known meaning, so the calling function knows what to deal with. For example, if your doSomething might throw an ArrayIndexNotFoundException if the widgets are not frobnicated, you might want to catch the ArrayIndexNotFoundException and throw a WidgetNotFrobnicatedException. Any time you throw an exception, your javadoc should specify exactly what circumstances will trigger that issue, so the user of your code has a chance to address this possible failure.
(there is one circumstance when I can see catching Exception, and that's if you want to fade to some graceful halt if things go wrong unexpectedly - in that case, in your catch block you'd log the issue, possibly alert a developer, and throw up some sort of "Sorry, error number 3542 has occurred, please restart the program" message.)
If your doSomething method, has the chance to throw an exception and you don't want to catch it, you should add this throws Exception on the method.
Unless it's an exception that you want to handle immediately in that method, it's good practice to use throws [specific Exception] so that the exception can be handled further up in the code.
It's somewhat commonplace to have a generic Throwable catch at the top that "gracefully crashes" in case something goes wrong.

Exception type created class used in another

I can't seem to find a way to fix this. I have a class called CardException which extends Exception. The only code it has is:
public class CardException extends Exception{
String erro;
public CartaoException(String erro){
this.erro = erro;
}
}
Now I have another class with a method in which I want to throw an Exception if the condition is false:
public void changePin(int pin, int newPin){
try{
if(pin == getPin()){
setPin(newPin);
}
} catch (CardException e){
System.out.println(e.getMessage());
}
}
but I'm getting an error at "catch (CardException e)" saying:
"Unreachable catch block for CardException. This exception is never thrown from the try statement body" and I have no idea why.
The point is to create a class called CardException of Exception type, with a constructor that receives an error message as argument. Then, on my other class, I need to create that method changePin which receives the old pin and a new pin and, if the old pin doesn't match the one already saved, it has to throw and exception with a message: "Invalid pin".
Java compiler is intelligent enough to determine whether the statements inside try blocks are prone to a checked exception or not. As no statement in your try block seems to cause CardException, hence compiler complains.
Just for the sake of testing, if you add throws clause with CardException to either of your getPin/setPin method, then compiler will not complain as those methods can throw the exception in catch block.
Since CardException extends Exception, not RuntimeException, it is considered a checked exception. What that means is that all methods from which the exception is thrown must declare the exception in their throws declaration clause.
Because of this requirement Java compilers can check if a code block throws a particular checked exception or not:
If there is a throws block inside the code body that throws this exception or one of its subclasses, the catch is valid
If any of the functions called inside the code body is declared as throwing the exception or one of its subclasses, the catch is valid
Otherwise, the catch is invalid, and the compiler issues an error.
You would need to catch this exception if getPin or setPin threw it. In this case, however, the functions would need to add a throws CardException to their declarations.

does throws exception leads the program to a pre written code

( patience requested as i'm new to programming )
when you add the phrase throws ABCexception in method declaration like this
public static void main(String[] args) throws ABCException {
}
does it mean that the you expect the method could generate an ABC exception and by writing throws ABCException ... when this exception occurs .. this exception will be caught and some prewritten code in java language will be executed corresponding to the ABCException. ?
thanks
throws declares that the method may throw the exception so the code that invoke this method must be prepare for it.
Being prepared for exception means that the code may catch the exception or re-throw it up.
Consider the constructor new FileInputStream(File pFile) which will create a FileInputStream from a File object. Since the file may not exist or not readable the constructor will throw FileNotFoundException (as declared).
So any code that call this constructor will either catch or rethrow it.
Catching it, the code will taking care of that exception by themself while rethrowing it, the code will let its caller take care of it.
Consider the following two codes:
Code 1: Catch -> Take care of it
public String readTextFile(File pFile) {
try {
FileInputStream FIO = new FileInputStream(pFile);
... // Do the reading and return
} catch (FileNotFoundException E) {
System.err.println("The file is not found");
}
}
Code 2: Throw -> Let the caller take care of ot
public String readTextFile(File pFile) throws FileNotFoundException {
FileInputStream FIO = new FileInputStream(pFile);
... // Do the reading and return
}
So the caller of readTextFile will have to catch or rethrow it too.
This mechanism ensures that someone have to take care of the exception in someway.
I hope I help.
The thows ABCException statement, before the function definition starts in earnest is just to indicate that this function may throw such an exception.
The actual throwing of the exception would happen within the code of the function. With code like the following (note the lack of an 's' at the end of "throw")
throw new ABCException();
The exceptions are then passed on "up" through the chain of the program logic that called this function this function, until one these "catches" the exception and deals with it. In case the exception "bubbles back" all the to the main() function, and if said exception isn't caught there either, a default handler deals with it, typically by printing out the exception to stderr/stdout and halting.
The way this exception could be caught would be with a try-catch construct, as in:
try
{
// do some stuff if needed
xy = fct(); // this fct may throw the ABCExeption...
// do more stuff as well
}
catch (ABCException e)
{
// for debugging you can do this
e.printStackTrace();
// otherwise you could deal with this exception as desired.
}
In re-reading the question, I noted that the function which is declared with throws ABCException and that is a bit odd, because main is the first method in the chain of function calls, meaning that there is nothing before main() which could catch an exception (other than the default exception handler of the Java Runtime, which wouldn't do anything specific for ABCException; it would just "dump it" to the console (or elsewhere for GUI-based apps) like any other exception.

Categories

Resources