1
|
- Professor
- Ismael H F Santos – ismael@tecgraf.puc-rio.br
|
2
|
- Linguagem de Programação JAVA
- Ismael H. F. Santos, Apostila
UniverCidade, 2002
- The Java Tutorial: A practical guide for programmers
- Tutorial on-line: http://java.sun.com/docs/books/tutorial
- Java in a Nutshell
- David Flanagan, O´Reilly &
Associates
- Just Java 2
- Mark C. Chan, Steven W. Griffith
e Anthony F. Iasi, Makron Books.
- Java 1.2
- Laura Lemay & Rogers
Cadenhead, Editora Campos
|
3
|
|
4
|
- Terminologia
- Exceção é a ocorrência de uma condição anormal durante a execução de um
método;
- Falha é a inabilidade de um método cumprir a sua função;
- Erro é a presença de um método que não satisfaz sua especificação.
- Em geral a existência de um erro gera uma falha que resulta em uma
exceção !
|
5
|
- Exceções & Modularidade
- O quinto critério de modularidade de Meyer estabelece a capacidade de
conter situações anormais dentro dos módulos.
- Para estarmos aptos a construir um sistema robusto, os métodos devem
sinalizar todas as condições anormais. Ou seja, os métodos devem gerar
exceções que possam ser tratadas para resolver ou contornar as falhas.
|
6
|
- Motivações para Exceções:
- 1) Um método pode detectar uma falha mas não estar apto a resolver sua
causa, devendo repassar essa função a quem saiba. As causas podem ser
basicamente de três tipos:
- Erros de lógica de programação;
- Erros devido a condições do ambiente de execução (arquivo não
encontrado, rede fora do ar, etc.);
- Erros irrecuperáveis (erro interno na JVM, etc);
- 2) Se introduzirmos o tratamento de falhas ao longo do fluxo normal de
código, podemos estar comprometendo muito a legibilidade (veremos um
exemplo adiante ).
|
7
|
|
8
|
- Exceções
- Diz-se que uma exceção é lançada para sinalizar alguma falha.
- O lançamento de uma exceção causa uma interrupção abrupta do trecho de
código que a gerou.
- O controle da execução volta para o primeiro trecho de código (na pilha
de chamadas) apto a tratar a exceção lançada.
|
9
|
- Suporte a Exceções
- As linguagens OO tipicamente dão suporte ao uso de exceções. Para
usarmos exceções precisamos de:
- uma representação para a exceção;
- uma forma de lançar a exceção;
- uma forma de tratar a exceção.
- Java suporta o uso de exceções:
- são representadas por classes;
- são lançadas pelo comando throw;
- são tratadas pela estrutura try-catch-finally.
|
10
|
- De modo geral, um método que lance uma exceção deve declarar isso
explicitamente. Para uma classe representar uma exceção, ela deve
pertencer a uma certa hierarquia.
- Considere a classe:
- public class Calc {
- public int div(int a, int b)
{
- return a/b;
- }
- }
- O método div, se for chamado com
b igual à zero, dará um erro.
Esse erro poderia ser sinalizado através de uma exceção
|
11
|
- Modelo de uma exceção indicando uma divisão por zero.
- public class DivByZeroEx extends
Exception {
- public String toString() {
- return “Division by zero.”;
- }
- }
- Classe com método sinalizando a exceção criada
- public class Calc {
- public int div(int a, int b) throws
DivByZeroEx {
- if (b == 0)
- throw new DivByZeroEx();
- return a/b;
- }
- }
- Podemos, então, quando utilizarmos o método div tratar a exceção, caso
ela ocorra.
|
12
|
- Tratando uma Exceção
- Calc calc = new Calc();
- try {
- int div = calc.div(1,1);
- System.out.println(div);
- } catch ( DivByZeroEx e ) {
- System.out.println(e);
- finally {
- ... // código que sempre é executado
- }
|
13
|
- Tratando Múltiplas Exceções
- try {
- ...
- } catch (Exception1 e1) {
- ...
- } catch (Exception2 e2) {
- ...
- } catch ( Exeception e ) {
- ... // trata todos os outros tipos de
exceções
- } finally {
- ...
- }
|
14
|
|
15
|
|
16
|
- Estrutura try-catch-finally
- Como apresentado, usamos try-catch para tratar uma exceção. A terceira
parte dessa estrutura, finally, especifica um trecho de código que será
sempre executado, não importando o que acontecer dentro do bloco try-catch.
- Não é possível deixar um bloco try-catch-finally sem executar sua parte
finally.
|
17
|
|
18
|
- Código protegido com tratamento de exceções
- Connection conexao = null;
- try {
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- conexao =
DriverManager.getConnection
(“jdbc:odbc:NorthWind”, ””,””);
- // Comunicação com o SGBD via
chamadas JDBC
- ....
- }catch (ClassNotFoundException
e) {
- System.out.println(“Driver não
encontrado” + e);
- }catch (SQLException sqle) {
- System.out.println(“Erro SQL:
” + sqle);
- }finally {
- if( conexao != null ) conexao.close();
- }
|
19
|
- errorCodeType readFile {
- initialize errorCode = 0;
- open the file;
- if ( theFileIsOpen ) {
- determine the length of the
file;
- if (gotTheFileLength) {
- allocate that much memory;
- if (gotEnoughMemory) {
- read the file into memory;
- if (readFailed) errorCode=
-1;
- } else errorCode = -2;
- } else {
- errorCode = -3;
- }
- close the file;
- if(fileDidntClose &&
errorCode==0) {
- errorCode = -4;
- } else {
- errorCode = errorCode and
-4;
- }
- } else { errorCode = -5; }
- return errorCode;
- }
|
20
|
- Tipos de Exceções em Java
- Checked Exceptions são exceções que devem ser usadas para modelar
falhas contornáveis. Devem sempre ser declaradas pelos métodos que as
lançam e precisam ser tratadas (a menos que explicitamente passadas
adiante);
- Unchecked Exceptions são exceções que devem ser usadas para modelar
falhas incontornáveis. Não precisam ser declaradas e nem tratadas.
|
21
|
- Checked Exceptions
- Para criarmos uma classe que modela uma Checked Exception, devemos
estender a classe Exception.
- Essa exceção será sempre verificada pelo compilador para garantir que
seja tratada quando recebida e declarada pelos métodos que a lançam.
|
22
|
- Unchecked Exceptions
- Esse tipo de exceção não será verificado pelo compilador. Tipicamente
não criamos exceções desse tipo, elas são usadas pela própria linguagem
para sinalizar condições de erro. Podem ser de dois tipos: Error ou RuntimeException.
- As Subclasses de Error não devem ser capturadas, pois representam
situações graves onde a recuperação é impossível ou indesejável.
- As Subclasses de RuntimeException representam erros de lógica de
programação que devem ser corrigidos (podem, mas não devem ser
capturadas: os erros devem ser corrigidos)
|
23
|
- Repassando Exceções
- Se quiséssemos usar o método div sem tratar a exceção, deveríamos
declarar que a exceção passaria adiante.
- public void f() throws DivByZeroEx {
- Calc calc = new Calc();
- int div = calc.div(a,b);
- System.out.println(div);
- ...
- }
|
24
|
- “Eu me comprometo a retornar uma referência para um objeto QueryResults.
Há a possibilidade de que uma exceção do tipo “SQLException” possa
acontecer enquanto eu estou tentando fazer isso para você. Se isso acontecer, eu
não irei tratar a exceção, mas
irei lançá-la para você.”
- Método execute
|
25
|
- try {
- try {
- ...
- } catch( FileNotFoundException e
) {
-
System.err.println("FileNotFoundException:
“+e.getMessage());
- throw new RuntimeException(e);
- }catch (IOException e) {
- class SampleException extends
Exception {
- public
SampleException(String msg) {super(msg);}
- public
SampleException(Throwable t) { super(t); }
- public
SampleException(String msg,Throwable t){super(msg,t);}
- }
- SampleException ex=new
SampleException("Other IOException", e);
- throw ex;
- }
- }catch (Exception cause) {
- System.err.println("Cause:
" + cause);
-
System.err.println("Original cause: " +
cause.getCause());
- }
|
26
|
- Informando mais dados sobre a Exceção
- ....
- }catch (Exception cause) {
- StackTraceElement elements[] =
cause.getStackTrace();
- for (int i=0; n=elements.length;
i < n; i++) {
-
System.err.println(elements[i].getFileName()+ ":“ +
-
elements[i].getLineNumber() + ">> " +
-
elements[i].getMethodName() + "()");
- }
- }
|
27
|
- Usando um arquivo de Log (java.util.logging)
- try {
- Handler handler = new
FileHandler("OutFile.log");
-
Logger.getLogger("").addHandler(handler);
- Logger logger = Logger.getLogger(
- "**[ verify
package:java.sun.example **]");
- StackTraceElement elems[] =
e.getStackTrace();
- for (int i = 0; n =
elems.length; i > n; i++) {
- logger.log(Level.WARNING,elems[i].getMethodName());
- }
- } catch (IOException logException) { System.err.println("Logging
error");
- }
|
28
|
- Encadeando Exceções (versão 1.4 em diante)
- try {
- InputStream fin = new
FileInputStream(args[0]);
- .....
- while((b=in.read()) != -1) {
System.out.print((char)b); }
- } catch (IOException e) {
- throw (HighLevelException) new
-
HighLevelException(e.getMessage()).initCause(e);
- }
- Um objeto Throwable contem um
snapshot da stack trace de sua thread quando de sua criação, alem disso
pode conter um outro objeto Throwable que foi responsável pela sua
criação. Isto implementa o mecanismo de chained exception.
- O metodo initCause salva internamente a exceção indicada para que a
stack trace possa ser impressa em uma instancia da exceção de nível superior, no
exemplo acima HighLevelException
|
29
|
- Exemplo: leitura de arquivo
- import java.io.*;
- public class PrintFile {
- public static void
main(String[] args) {
- try {
- InputStream fin = new
FileInputStream(args[0]);
- InputStream in = new
BufferedInputStream(fin);
- int b;
- while((b=in.read()) != -1)
{ System.out.print((char)b);}
- } catch (IOException e) {
- System.out.println(e);
- } finaly {
- if (fin != null)
fin.close();
- }
- } Exercícios
– Questão 10
- }
|
30
|
- Exemplo: Impressão para arquivo
- import java.io.*;
- public void writeList(Vector v) {
- PrintWriter out = null;
- try {
-
System.out.println("Entering try statement");
- out = new PrintWriter(new
FileWriter("OutFile.txt"));
- for (int i = 0; i > size;
i++) {
- out.println("Value
at: " +i+ "=" +v.elementAt(i));
- }
- } catch (FileNotFoundException
e) {
-
System.err.println("FileNotFoundException:"+e.getMessage());
- } catch (IOException e) {
-
System.err.println("Caught IOException: " +
e.getMessage());
- } finally {
- if (out != null) {
-
System.out.println("Closing PrintWriter");
out.close();
- }else {
System.out.println("PrintWriter not open"); }
- }
- }
|
31
|
|
32
|
|
33
|
- Construtores de Exception
- Exception ()
- Exception (String message)
- Exception (String message, Throwable cause) [Java 1.4]
- Métodos de Exception
- String getMessage() - retorna mensagem passada pelo construtor
- Throwable getCause() - retorna exceção que causou esta exceção [Java
1.4]
- String toString() - retorna nome da exceção e mensagem
- void printStackTrace() - Imprime detalhes (stack trace) sobre exceção
|
34
|
|
35
|
|
36
|
|
37
|
|
38
|
|
39
|
|
40
|
|
41
|
|
42
|
- Exceptions due to programming errors
- In this category, exceptions are generated due to programming errors
(e.g., NullPointerException and IllegalArgumentException). The client
code usually cannot do anything about programming errors.
- Exceptions due to client code errors
- Client code attempts something not allowed by the API, and thereby
violates its contract. The client can take some alternative course of
action, if there is useful information provided in the exception. For
example: an exception is thrown while parsing an XML document that is
not well-formed. The exception contains useful information about the
location in the XML document that causes the problem. The client can
use this information to take recovery steps.
- Exceptions due to resource failures
- Exceptions that get generated when resources fail. For example: the
system runs out of memory or a network connection fails. The client's
response to resource failures is context-driven. The client can retry
the operation after some time or just log the resource failure and
bring the application to a halt.
|
43
|
- Checked exceptions
- Exceptions that inherit from the Exception class are checked exceptions.
Client code has to handle the checked exceptions thrown by the API,
either in a catch clause or by forwarding it outward with the throws
clause.
- Unchecked exceptions
- RuntimeException also extends from Exception. However, all of the
exceptions that inherit from RuntimeException get special treatment.
There is no requirement for the client code to deal with them, and
hence they are called unchecked exceptions.
- C++ and C# do not have checked exceptions at all; all exceptions in
these languages are unchecked.
|
44
|
- When deciding on checked exceptions vs. unchecked exceptions, ask
yourself, "What action can the client code take when the exception
occurs?"
|
45
|
- Preserve encapsulation
- Never let implementation-specific checked exceptions escalate to the
higher layers. For example, do not propagate SQLException from data
access code to the business objects layer. Business objects layer do
not need to know about SQLException. You have two options:
- Convert SQLException into another checked exception, if the client
code is expected to recuperate from the exception.
- Convert SQLException into an unchecked exception, if the client code
cannot do anything about it.
|
46
|
- public void dataAccessCode(){
- try{ ..some code that throws
SQLException
- } catch(SQLException ex){
ex.printStacktrace(); }
- }
- This catch block just suppresses the exception and does nothing. The
justification is that there is nothing my client could do about an
SQLException. How about dealing with it in the following manner?
- public void dataAccessCode(){
- try{ ..some code that throws
SQLException
- } catch(SQLException ex){
- throw new RuntimeException(ex);
- }
- }
|
47
|
- Try not to create new custom exceptions if they do not have useful
information for client code.
- public class DuplicateUsernameException extends Exception{}
- The new version provides two useful methods: requestedUsername(), which
returns the requested name, and availableNames(), which returns an array
of available usernames similar to the one requested.
- public class DuplicateUsernameException extends Exception {
- public
DuplicateUsernameException (String username){....}
- public String
requestedUsername(){...}
- public String[]
availableNames(){...}
- }
|
48
|
- Document exceptions
- You can use Javadoc's @throws tag to document both checked and
unchecked exceptions that your API throws. Or write unit tests to
document exceptions.
- public void testIndexOutOfBoundsException() {
- ArrayList blankList = new
ArrayList();
- try {
- blankList.get(10);
- fail("Should raise an
IndexOutOfBoundsException");
- } catch
(IndexOutOfBoundsException success) {}
- }
|
49
|
- Always clean up after yourself
- If you are using resources like database connections or network
connections, make sure you clean them up.
- public void dataAccessCode(){
- Connection conn = null;
- try{
- conn = getConnection();
- ..some code that throws
SQLException
- } catch( SQLException ex ) {
- ex.printStacktrace();
- } finally{
- DBUtil.closeConnection(conn);
- }
- }
|
50
|
- Always clean up after yourself (cont.)
- class DBUtil{
- public static void
closeConnection (Connection conn) {
- try{
- conn.close();
- } catch(SQLException ex) {
- logger.error("Cannot
close connection");
- throw new
RuntimeException(ex);
- }
- }
- }
- DBUtil is a utility class that closes the Connection. The important
point is the use of finally block, which executes whether or not an
exception is caught. In this example, the finally closes the connection
and throws a RuntimeException if there is problem with closing the
connection.
|
51
|
- Never use exceptions for flow control
- Generating stack traces is expensive and the value of a stack trace is
in debugging. In a flow-control situation, the stack trace would be
ignored, since the client just wants to know how to proceed.
- public void useExceptionsForFlowControl() {
- try {
- while(true) { increaseCount();
}
- } catch
(MaximumCountReachedException ex) {
- } //Continue execution
- }
- public void increaseCount() throws MaximumCountReachedException { if
(count >= 5000) throw new MaximumCountReachedException();
- }
|
52
|
- Do not suppress or ignore exceptions
- When a method from an API throws a checked exception, it is trying to
tell you that you should take some counter action.
- Do not catch top-level exceptions
- Unchecked exceptions inherit from the RuntimeException class, which in
turn inherits from Exception. By catching the Exception class, you are
also catching RuntimeException as in the following code:
- try{
- ..
- } catch( Exception ex ){ }
|
53
|
- Log exceptions just once
- Logging the same exception stack trace more than once can confuse the
programmer examining the stack trace about the original source of
exception. So just log it once.
|
54
|
|
55
|
- Expressões booleanas que o programador define para afirmar uma condição
que ele acredita ser verdade
- Asserções são usadas para validar código ( ter a certeza que um vetor
tem determinado tamanho, ter a certeza que o programa não passou por
determinado lugar, etc)
- Melhoram a qualidade do código: tipo de teste caixa-branca
- Devem ser usadas durante o desenvolvimento e desligadas na produção
(afeta a performance)
- Não devem ser usadas como parte da lógica do código
- Asserções são um recurso novo do JSDK1.4.0
- Nova palavra-chave: assert
- É preciso compilar usando a opção -source 1.4:
- >javac -source 1.4 Classe.java
- Para executar, é preciso habilitar afirmações (enable assertions):
|
56
|
- Asserções testam uma condição. Se a condição for falsa, um AssertionError
é lançado
- Sintaxe:
- assert expressão;
- assert expressãoUm : expressãoDois;
- Se primeira expressão for true, a segunda não é avaliada. Sendo falsa,
um AssertionError é lançado e o valor da segunda expressão é passado no
seu construtor.
|
57
|
- Trecho de código que afirma que controle nunca passará pelo default:
- switch( estacao ) {
- case Estacao.PRIMAVERA:
- ...
- break;
- case Estacao.VERAO:
- ...
- break;
- case Estacao.OUTONO:
- ...
- break;
- case Estacao.INVERNO:
- ...
- break;
- default:
- assert false: "Controle nunca deveria chegar aqui!";
- }
|