How do I use the words Throws
and Throw
in a Java code?
How do I use the words Throws
and Throw
in a Java code?
throws
is part of the method declaration of your signature. It defines part of the API. Indicates that a piece of code that calls this method must capture a possible exception that it throws. Even if you do not wish to do anything with the exception, it must be captured and re-released. Or you should indicate that the method that uses another with a possible exception has a throw
, as below:
public void M1() throws IOException {
FileReader f = new FileReader("notExist.txt");
}
In this case, any method that calls M1
must treat the IOException
exception with a try
or indicate that it throws the same specified exception at M1
.
It may appear that there is no exception in this method, but FileReader
throws an exception FileNotFoundException
which is derived from IOException
. The signature of the constructor FileReader
method requires its handling. The inclusion of throws IOException()
in the method signature guarantees the handling by delegating to the caller of M1
to handle properly.
One of the ways to treat (example rough):
try {
M1();
} cath (IOException e) {
System.out.println("Deu erro no arquivo");
}
Another method froma that does not compile:
public void M1() {
FileReader f = new FileReader("notExist.txt");
}
No treatment was given, it did not catch the exception and did not instruct the compiler to be the responsibility of the M1
caller.
It can be considered a compiler directive to check if due treatment is being given. It is handled at compile time.
There is a lot of controversy whether this is good or bad for an application. Often more is used as% as it should and it is extremely common for "pretending" programmers to be dealing with it, since a real treatment is required (it does not have as a compiler to force this). In many cases this is a bad thing for the application, but there are cases that there really is nothing correct and feasible that can be done, but the API requires that the exception be handled.
It is recommended that some types of exceptions be handled. Others do not. Programming errors or any unrecoverable errors do not need and should not be handled. Exceptions where the program can actually take some action and solve the problem (very common in accessing external resources) are likely to make the checked exception call with the throws
declaration. A throws
should normally be treated, it is a recoverable error . Another example is IOException
. Since a SQLException
or the exceptions derived from NullPointerException
would be absurd to require a treatment, since it is a programming error and there is nothing sure that can be done to get around the problem.
RunTimeExcepetion
is a statement , it has the exception thrown .
public void M2() {
throw new IOException();
}
This method throws an exception but does not require it to be handled by its callers. It transfers flow control to calling methods. It uses what is called unckecked exception , that is, an exception is thrown but nothing compels it to be handled. It is handled at runtime.
Full code examples here , here , here and here .
More examples:
import java.io.*;
public class Estudos{
public static void main(String[] args){
try{
DataInputStream in = new DataInputStream(
new BufferedInputStream(
new FileInputStream("conteudo.txt")));
while(in.available() != 0)
System.out.print((char) in.readByte());
}
catch(IOException e){
System.out.print(e.getMessage());
}
System.exit(0);
}
}
Note that throw
, DataInputStream
do not enforce exceptions, but BufferedInputStream
must have FileInputStream
required, according to documentation. The treatment was generalized to any percentage of%.
import java.util.*;
class Estudos {
public static void main(String[] args) {
String palavra = "Java";
Scanner in = new Scanner(System.in);
System.out.print("Informe um inteiro: ");
int indice = in.nextInt();
try {
System.out.println("O caractere no índice informado é " + palavra.charAt(indice));
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("Erro:" + e.getMessage());
}
}
}
See running on ideone . Also I put it in GitHub for future reference .
In this example, a FileNotFoundException
ception that could be generated in IOException
", but nothing forces this to be done.
One is part of the method signature, the other executes the throwing of an exception by diverting the execution flow of the algorithm.
With these examples and the others of the other answers, I think it helps you a lot. Please let me know if you need more specific information. Get used to reading documentation. It will do this for a lifetime:)
The throw
keyword serves to throw an exception (more precisely a Throwable
, but in 99.9% of cases an exception). The throws
keyword is used to declare that a method can throw exceptions of a certain type.
To better understand what it means to be able to throw exceptions, let's see.
This is the hierarchy of the Throwable
classes (the ExcecaoA
, ExcecaoB
, ExcecaoC
, and ExcecaoD
classes are invented and are only given as examples):
Throwable
|
____|____
| |
Exception Error
|
____|__________________
| | |
ExcecaoA ExcecaoB RuntimeException
|
____|____
| |
ExcecaoC ExcecaoD
Let's focus on the subclasses of Exception
and RuntimeException
, which are the most common cases.
In Java there are two types of exceptions:
Exception
but not RuntimeException
), having as examples in our hierarchy the classes ExcecaoA and ExcecaoB; RuntimeException
), having as examples in our hierarchy the classes ExececaoC and ExececaoD. >
When I say "treated at compile time", I mean that if a given exception is thrown within a method with the keyword throw
, that same method should capture the exception or declare that it throws by means of the throws
clause (which effectively means delaying catching the exception for other methods that call this method). In the case of subclasses of RuntimeException
, this treatment is not necessary, and the exception in question can be thrown by any part of the code in any situation.
When the running code arrives at a line containing the throw
keyword, note that this line is inside a method that is inside another method, and so on, ie during code execution there a stack of methods execution. When throw
is executed and the exception is thrown, it is propagated along the method execution stack until it reaches the end of the stack or is trapped by a catch
block, which allows you to handle this exception, relaunch it, or throw a new exception of a different type back to the stack of running methods.
For more details, see the Exceptions lesson in the Oracle Java Tutorial.
Suppose you want to create a method whose input can not be less than zero.
Use throw
to throw an exception in this case:
if (numero < 0) {
throw new Exception("Número não pode ser menor que zero!");
}
The throws
statement is used in a method to indicate that it throws a particular Exception:
public void fazAlgo(int numero) throws Exception {
if (numero < 0) {
throw new Exception("Número não pode ser menor que zero!");
}
// resto do método
}
Of course the one recommended is to create your own Exceptions:
class NumeroMenorQueZeroException extends Exception {
// sua classe
}
So the statement would look like this:
class MinhaClasse {
// o "throws" no método abaixo indica que ele lança
// a exceção "NumeroMenorQueZeroException", que criamos acima
public void fazAlgo(int numero) throws NumeroMenorQueZeroException {
if (numero < 0) {
throw NumeroMenorQueZeroException("Numero não pode ser menor que zero!");
} else {
// faz algo com o número maior ou igual a zero
}
}
}
The try/catch
would look like this:
try {
minhaClasse = new MinhaClasse();
minhaClasse.fazAlgo(-1);
} catch (NumeroMenorQueZeroException e) {
JOptionPane.showMessageDialog(null, "Um erro aconteceu: " + e);
}
You can read more about Exceptions here: link
Throws You are throwing an exception, example
public void acordar() throws Exception {
throw new Exception("opa, deu erro");
}
That is, you are "telling" who to call this method that it MAY (does not mean that it will, as in the example) explode an exception.
Throw You are "trying" an exception, as in example 1
throw new Exception("opa, deu erro");
As you can see it is popping an exception