EXCEÇÕES

A EXPERIÊNCIA MOSTRA QUE PROGRAMADORES

TIPOS DE ERROS

TRATAR TODOS OS ERROS É DIFÍCIL PORQUE DEIXA O CÓDIGO COMPLETAMENTE ILEGÍVEL

O MECANISMO DE EXCEÇÕES DE JAVA DEIXA EXPLICÍTOS OS ERROS TRATADOS POR UM MÉTODO

UMA EXCEÇÃO É LANÇADA QUANDO UMA CONDIÇÃO NÃO ESPERADA DE ERRO É ENCONTRADA

UMA EXCEÇÃO É CAPTURADA QUANDO ALGUÉM "ACIMA" (NA PILHA DE EXECUÇÃO) TRATA O ERRO

CRIAÇÃO DE TIPOS DE EXCEÇÃO


public class ExcecaoAtributoInexistente extends Exception {
   public String nomeAtributo;  // os dados que geraram o erro

   ExcecaoAtributoInexistente( String nome ) {
      super( "Nao tem atributo chamado \"" + nome + "\"" );
      nomeAtributo = nome;
   }
}

A CLÁUSULA throw


public void substituiValor( String nome, Object novoValor )
     throws ExcecaoAtributoInexistente {
   Atributo atrib = localiza( nome );  // procura o atributo
   if( atrib == null ) {               // se não for localizado
      throw new ExcecaoAtributoInexistente( nome );
   }
   atrib.setValor( novoValor );
}

A CLÁUSULA throws

AS CLÁUSULAS try, catch E finally


   try {
      comandos
   } catch( TipoDeExceção1 identificador1 ) {
      comandos
   } catch( TipoDeExceção2 identificador2 ) {
      comandos
   ...
   } finally {
      comandos
   }

   Object valor = new Integer(1999); // Explique por que não usa int
   try {
      carroComAtributos.substituiValor( "DataFabricação", valor );
   } catch( ExcecaoAtributoInexistente e ) {
      // Nao deveria ocorrer, mas recupera caso ocorra
      Atributo atrib = new Atributo( e.nomeAtributo, valor );
      carroComAtributos.adiciona( atrib );
   }

O finally PODE SER USADO SEM EXCEÇÕES PARA SIMPLIFICAR O CÓDIGO DE LIMPEZA


public boolean procuraPor( String arquivo, String palavra )
    throws IOException {
   BufferedReader input = null;

   try {
      input = new BufferedReader(
                  new InputStreamReader(
                      new FileInputStream( arquivo ) ) );
      StreamTokenizer st = new StreamTokenizer( input );
      while( st.nextToken() != StreamTokenizer.TT_EOF ) {
         if( palavra.equals( st.toString() ) ) {
            return true;
         }
      }
      return false;
   } finally {
      if( input != null ) {
         input.close();
      }
   }
}

QUANDO USAR EXCEÇÕES


   while( (token = stream.next()) != Stream.END ) {
      processa( token );
   }
   stream.close();

   try {
      for(;;) {
         processa( stream.next() );
      }
   } catch( StreamEndException e ) {
      stream.close();
   }

JAVA-27 home programa anterior próxima