Using the keywords Throws and Throw

Asked

Viewed 33,277 times

22

How do I use the words Throws and Throw in a Java code?

  • 1

    Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

4 answers

25

Checked Exception

throws is part of the method statement, of his signing. It defines part of the API. It indicates that a chunk of code that calls this method must necessarily capture a possible exception that it throws. Even if you do not wish to do anything with the exception, it must be captured and relaunched. Or it 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 you call M1() must deal with the exception IOException with a try or indicate that it casts the same exception specified in M1().

It may seem that there is no exception in this method, but the FileReader throws an exception FileNotFoundException which is derived from the IOException. The signature of the constructor method FileReader requires a treatment of it. The inclusion of throws IOException() in the signature method ensures the treatment delegating to the caller of M1() treat appropriately.

One of the ways to treat (crude example):

try { 
    M1();
} cath (IOException e) {
    System.out.println("Deu erro no arquivo");
}

Another form of the method that does not compile:

public void M1() {
    FileReader f = new FileReader("notExist.txt");
}

No treatment was given, did not capture the exception and did not indicate to the compiler that it should be the responsibility of the caller of M1().

He may be regarded as a compiler directive check if proper treatment is being given. It is treated at compile time.

There is much controversy whether this is good or bad for an application. Often more is used throws than it should and is extremely common for programmers to "pretend" that they are dealing with, since it is not mandatory to have a real treatment (there is no way for a compiler to force this). In many cases this is a bad thing for the application, but there are cases where there really isn’t anything right and workable that can be done, but the API requires the exception to be handled.

It is recommended that some types of exceptions be dealt with obligatorily. Others are not. Programming errors or any unrecoverable errors do not need and should not be dealt with. Exceptions where the program can actually take some action and solve the problem (very common in access to external resources) are likely to make the call checked Exception with the declaration of throws. One IOException normally should be treated, is a recoverable error. Another example is a SQLException. Already one NullPointerException or the exceptions derived from RunTimeExcepetion it would be absurd to require a treatment, since it is programming error and there is nothing safe that can be done to get around the problem.

Make an exception

throw is a statement, he have the exception be cast.

public void M2() {
    throw new IOException();
}

This method throws an exception but does not require that it be treated by its callers. It transfers the flow control for the calling methods. He uses what is called unckecked Exception, that is, an exception is thrown but nothing requires it to be dealt with. It is dealt with at runtime.

Examples of complete code 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 DataInputStream, BufferedInputStream do not require exceptions to be dealt with, but FileInputStream need to have FileNotFoundException treated as obligatory, according to documentation. The treatment was made in a general way for any IOException.

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());
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

In this example it was an exception StringIndexOutOfBoundsException which could be generated in charAt(), but nothing requires this to be done.

Completion

One is part of the signature of the method the other executes the release of an exception by deviating the execution flow of the algorithm.

With these examples and the others of the other answers, I think it helps you a lot. Let us know if you need more specific information. Get used to reading documentation. You will do this all your life :)

8

The keyword throw serves to cast an exception (more precisely a Throwable, but in 99.9% of cases an exception). The keyword throws to declare that a method may make exceptions of a particular type.

To better understand what "being able to make exceptions" means, let’s see.

This is the hierarchy of classes Throwable (the classes ExcecaoA, ExcecaoB, ExcecaoC and ExcecaoD are invented and were placed only 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:

  1. Checked exceptions: those that need to be treated at compile time (are subclasses of Exception but not of RuntimeException), having as examples in our hierarchy the classes Excecaoa and Excecaob;

  2. Unchecked exceptions: those that do not need to be treated at compile time (are subclasses of RuntimeException), having as examples in our hierarchy the classes Excecaoc and Excecaod.

When I say "dealt with at compile time", I mean that if a particular exception is cast within a method by means of the keyword throw, that same method should capture the exception or else declare that the throws (which means effectively postponing the catch of the exception to other methods that call this method). In the case of subclasses of RuntimeException, such treatment is not necessary, and the exception in question may be released by any part of the code in any situation.

When running code reaches a line containing the keyword throw, note that this line is within a method that is within another method and so on, that is, during code execution there is a stack of methods. The moment the throw is executed and the exception is thrown, it is propagated along the stack of execution methods until you reach the end of the stack or else be captured by a block catch, which allows you to treat this exception, relaunch it, or launch a new exception of a different type back to the method execution stack.

For more details, see the lesson Exceptions in the Oracle Java Tutorial ().

  • 1

    Thanks @Piovezan but it would be possible to send a code ready with the words, is that I am beginner in java. Thanks.

7

Suppose you want to create a method whose input cannot be less than zero.

Use throw to make an exception in this case:

if (numero < 0) {
  throw new Exception("Número não pode ser menor que zero!");
}

The statement throws is used in a method to indicate that it throws a certain 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 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: http://www.caelum.com.br/apostila-java-orientacao-objetos/excecoes-e-controle-de-erros/

  • 1

    Thanks for the explanation but it would be possible within a ready code. It’s just that I’m a beginner in java. @Andrey

  • 1

    @Betobarroso I deepened my answer a little. If that’s not what you want, edit your question being more specific. =)

3

  • Throws You’re making an exception, example

    public void acordar() throws Exception {
        throw new Exception("opa, deu erro");
    }
    

That is, you are "telling" to whomever call this method that he CAN (does not mean 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 he’s bursting an exception

Browser other questions tagged

You are not signed in. Login or sign up in order to post.