Buscar

Aula 13 - Tratamento de Exceções

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes
Você viu 3, do total de 41 páginas

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes
Você viu 6, do total de 41 páginas

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes
Você viu 9, do total de 41 páginas

Faça como milhares de estudantes: teste grátis o Passei Direto

Esse e outros conteúdos desbloqueados

16 milhões de materiais de várias disciplinas

Impressão de materiais

Agora você pode testar o

Passei Direto grátis

Você também pode ser Premium ajudando estudantes

Prévia do material em texto

Projeto de Software / Programação 3 
Tratamento de Exceções 
Márcio Ribeiro 
marcio@ic.ufal.br 
twitter.com/marciomribeiro 
2 
What	
  can	
  go	
  wrong?!	
  
result = n1 / n2;	
In the following slides: 
 
1) Analyze the code; 
2) read the documentation; 
3) and tell me what can go wrong 
System.out.println("Enter the first number: ");	
int n1 = Integer.parseInt(input.next());	
Reader reader = new FileReader("shopping-cart.json");	
Excep2ons!	
  
6 
NumberFormatExcep2on	
  
Exception in thread "main" java.lang.NumberFormatException:	
 For input string: "e”	
 at java.lang.NumberFormatException.	
 forInputString(NumberFormatException.java:48)	
 at java.lang.Integer.parseInt(Integer.java:449)	
 at java.lang.Integer.parseInt(Integer.java:499)	
 at Calculadora.main(Calculadora.java:21)	
Message 
Exception type 
Exception trace 
Where it happened 
7 
FileNotFoundExcep2on	
  
java.io.FileNotFoundException: shopping-cart.json	
 (No such file or directory)	
 at java.io.FileInputStream.open(Native Method)	
 at java.io.FileInputStream.<init>(FileInputStream.java:120)	
 at java.io.FileInputStream.<init>(FileInputStream.java:79)	
 at java.io.FileReader.<init>(FileReader.java:41)	
 at Calculadora.main(Calculadora.java:14)	
8 
What	
  is	
  an	
  excep2on?!	
  
§  Shorthand	
  for	
  the	
  phrase	
  “excep2onal	
  event”	
  
“An exception is an event, which occurs during 
the execution of a program, that disrupts the 
normal flow of the program's instructions.” 
From	
  http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html	
  
9 
Why	
  they	
  are	
  important?	
  
§  Excep2ons	
  have	
  informa2on	
  about	
  the	
  error	
  that	
  happened	
  
§  Makes	
  our	
  programs	
  (more)	
  fault	
  tolerant…	
  
Tamirys
Nota
Existe uma área de computação chamada tolerância a falhas. Se der algum problema no sistema, a empresa tenta replicar o sistema de modo que ele tente recurar o serviço com um plano B.
10 
Again:	
  an	
  excep2on	
  is	
  an	
  event…	
  
§  …	
  that	
  happened	
  when	
  execu2ng	
  the	
  program…	
  
§  …	
  that	
  interrupted	
  the	
  normal	
  flow	
  execu2on	
  
§  When	
  this	
  event	
  occurs…	
  
§  …	
  an	
  Excep2on	
  object	
  is	
  created	
  
§  This	
  object	
  encapsulates	
  the	
  excep2on	
  informa2on…	
  
§  …	
  and	
  provides	
  methods	
  to	
  manipulate	
  this	
  informa2on	
  
Tamirys
Realce
11 
There	
  are	
  two	
  responsibili2es	
  
Someone creates the exception… 
new Exception();	
… and someone can handle it! 
catch (Exception e) { … }	
Tamirys
Nota
Se a "bomba" não for tratada, o sistema não é tolerante a falhas.
12 
Excep2on	
  handling	
  
§  “Process	
  of	
  responding	
  to	
  the	
  occurrence	
  of	
  excep2ons	
  oMen	
  
changing	
  the	
  normal	
  flow	
  of	
  program	
  execu2on”	
  
§  Examples	
  
§  Wrong	
  input?	
  
•  Ask	
  again	
  for	
  a	
  right	
  one!	
  
§  Locked	
  file?	
  Network	
  problems?	
  GPS	
  wai2ng	
  for	
  loca2on	
  error?	
  
•  Wait	
  a	
  second	
  and	
  try	
  again!	
  
§  End	
  of	
  the	
  world?	
  
•  Shows	
  at	
  least	
  a	
  decent	
  message	
  explaining	
  what’s	
  going	
  on…	
  
From	
  http://en.wikipedia.org/wiki/Exception_handling	
  
How	
  to	
  handle	
  excep2ons	
  
In	
  Java?!	
  
15 
We	
  already	
  know…	
  
§  …	
  where	
  the	
  excep2ons	
  come	
  from!	
  
System.out.println("Enter the first number: ");	
int n1 = Integer.parseInt(input.next());	
Reader reader = new FileReader("shopping-cart.json");	
Where should we handle them?! 
16 
Inside	
  the	
  method	
  where	
  it	
  can	
  be	
  raised…	
  
public void loadInput() {	
 Scanner input = new Scanner(System.in);	
 boolean correctInput = false;	
	 		
 while (!correctInput) {	
 try {	
 System.out.println("Enter the first number: ");	
 n1 = Integer.parseInt(input.next());	
	 		
 System.out.println("Enter the second number: ");	
 n2 = Integer.parseInt(input.next());	
	 	 		
 correctInput = true;	
 } catch (NumberFormatException e) {	
 System.out.println("Wrong input. " +	
 "You typed a value that is not an integer. " +	
 e.getMessage());	
 }	
 }	
}	
Tamirys
Nota
Tenta executar o código entre chaves...
Tamirys
Nota
Se não funcionar o código entre chaves, então entra na exceção.
17 
Externally	
  
public void loadInput() throws NumberFormatException,	
 FileNotFoundException {	
	
 Scanner input = new Scanner(System.in);	
 System.out.println("Enter the first number: ");	
 this.n1 = Integer.parseInt(input.next());	
	 		
 System.out.println("Enter the second number: ");	
 this.n2 = Integer.parseInt(input.next());	
	
 this.jsonFileReader = new FileReader("shopping-cart.json");	
	
}	
Tamirys
Nota
Levanta exceções. Quem chama o método que tem que tratar.
18 
The	
  method	
  which	
  calls	
  loadInput	
  handles!	
  
public void process() {	
 boolean ready = false;	
	
 while (!ready) {	
 try {	
	loadInput();	
	ready = true; 	
 } catch (NumberFormatException e) {	
	System.out.println("Wrong input. "	
	 	+ "You typed a value that is not an integer. "	
	 	 	+ e.getMessage());	
 } catch (FileNotFoundException e) {	
	System.out.println("File not available yet. "	
	 	+ "Wait few seconds until it is created...");	
 }	
 }	
	 		
 //process...	
}	
From	
  http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html	
  
20 
Stack	
  trace	
  
§  getMessage()	
  
•  String	
  that	
  contains	
  the	
  excep2on	
  descrip2on	
  
§  printStackTrace()	
  
main() method1() method2() 
Stack 
java.lang.Exception: Exception thrown in metodo2 
at ShoppingCart.method2(ShoppingCart.java:9) 
at ShoppingCart.method1(ShoppingCart.java:10) 
at ShoppingCart.main(ShoppingCart.java:41) main() 
method1() 
method2() 
21 
This	
  code	
  works	
  fine…	
  
public void process() {	
 boolean ready = false;	
	
 while (!ready) {	
 try {	
	loadInput();	
	ready = true; 	
 } catch (FileNotFoundException e) {	
	System.out.println("File not available yet. "	
	 	+ "Wait few seconds until it is created...");	
 }	
 }	
	 		
 //process...	
}	
Why? 
22 
Three	
  kinds	
  of	
  excep2ons	
  
§  Checked	
  excep2ons	
  
§  Subject	
  to	
  catch	
  blocks	
  
§  Examples:	
  FileNotFoundExcep2on,	
  SocketExcep2on	
  
§  Error	
  
§  Not	
  subject	
  to	
  catch	
  blocks	
  
§  External	
  to	
  the	
  applica2on:	
  usually	
  cannot	
  recover	
  
§  Examples:	
  OutOfMemoryError,	
  StackOverflowError	
  
	
  
§  Run2me	
  excep2ons	
  
§  Not	
  subject	
  to	
  catch	
  blocks	
  
§  Usually:	
  programming	
  bugs,	
  improper	
  use	
  of	
  an	
  API	
  
§  Examples:	
  ArrayIndexOutOfBoundsExcep2on,	
  NullPointerExcep2on	
  
Tamirys
Nota
Memória de Pilha (Stack): Não utiliza alocação dinâmica de memória. Quando for dado new em alguma coisa, a alocação de memória pode ser grande... Se for muito grande, é colocado em uma Heap. Se for muito grande, dará StackOverflowError e foge do controle,ou seja, não dá para recuperar.
Tamirys
Nota
ERRO DO PROGRAMADOR! BUGS DE PROGRAMAÇÃO!! RESOLVA!
Tamirys
Nota
API: Conjunto de classes. Ex.: Colections.
So,	
  Excep2ons	
  are	
  classes...	
  
Throwable!
Error! Exception!
SortedSet!SortedSet!…!
RuntimeException!
…!
…!
Object! Unchecked 
Excep2ons	
  are	
  classes...	
  
And	
  they	
  use	
  inheritance...	
  
So,	
  can	
  I	
  define	
  my	
  own	
  excep2on?	
  
public class CannotSaveShoppingCartException extends Exception {	
	
 public CannotSaveShoppingCartException () {	
 super("Cannot save shopping cart.");	
 }	
		
 public CannotSaveShoppingCartException (String message) {	
 super(message);	
 }	
}	
public class CannotSaveShoppingCartException	
 extends RuntimeException {	
	
 publicCannotSaveShoppingCartException () {	
 super("Cannot save shopping cart.");	
 }	
		
 public CannotSaveShoppingCartException (String message) {	
 super(message);	
 }	
}	
Chec
ked 
Unch
ecked
 
Tamirys
Nota
Quem chama o método que chama é o throws é obrigado a utilizar o try catch.
27 
Raising	
  excep2ons	
  
public class FilePersistence implements PersistenceSession {	
	
 @Override	
 public void save(ShoppingCart shoppingCart)	
 throws CannotSaveShoppingCartException {	
 try {	
	
 //do something that can raise IOException	
 	
 } catch (IOException e) {	
	
 throw new CannotSaveShoppingCartException(	
 "File 'shopping-carts.ufal' cannot be 	
 created or was not found");	
 }	
 }	
}	 Need to update the 
PersistenceSession interface! 
Be	
  aware	
  of	
  the	
  flow!	
  
29 
Can	
  you	
  see	
  any	
  problem	
  with	
  “out”?	
  
try {	
	 	 	
 // …	
 out.close();	
	 	 	
} catch (FileNotFoundException e) {	
	
 System.err.println("FileNotFoundException: "+e.getMessage());	
 throw new RuntimeException(e);	
	
} catch (IOException e) {	
	
 System.err.println("Caught IOException: " + e.getMessage());	
	
}	
If	
  an	
  excep2on	
  occurs,	
  
“out”	
  is	
  never	
  closed...	
  
31 
What	
  about	
  this	
  solu2on?	
  
try {	
	 	 	
 // …	
 out.close();	
	 	 	
} catch (FileNotFoundException e) {	
 	
 out.close();	
 System.err.println("FileNotFoundException: "+e.getMessage());	
 throw new RuntimeException(e);	
	
} catch (IOException e) {	
	
 System.err.println("Caught IOException: " + e.getMessage());	
	
}	
What	
  is	
  going	
  on?	
  
Cloned code 
33 
Finally	
  block	
  
try {	
	
 //do something that can raise IOException	
 	
} catch (IOException e) {	
	
 //handles the IOException	
	
} finally {	
	
 //always executed	
	
}	
§  The	
  finally	
  block	
   is	
   always	
  executed	
  whether	
  an	
  excep2on	
   is	
  
raised	
  or	
  not	
  
34 
Important	
  
“The finally block is a key tool for preventing 
resource leaks. When closing a file or otherwise 
recovering resources, place the code in a finally 
block to ensure that resource is always recovered.” 
From	
  http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html	
  
35 
Finally	
  block	
  in	
  ac2on!	
  
finally {	
	
 if (out != null) { 	
	
 System.out.println("Closing PrintWriter");	
 out.close(); 	
	
 } else { 	
	
 System.out.println("PrintWriter not open");	
	
 } 	
	
}	
§  Closing	
  the	
  PrintWriter…	
  
Excep2ons	
  in	
  Java	
  SE	
  7	
  
37 
Raising	
  excep2ons	
  within	
  the	
  finally	
  block…	
  
try {	
 URL url = new URL("http://www.yoursimpledate.server/");	
 reader = new BufferedReader(new 	
 InputStreamReader(url.openStream()));	
 String line = reader.readLine();	
 Date date = new SimpleDateFormat("MM/DD/YY").parse(line);	
} catch (MalformedURLException exception) {	
 // handle passing in the wrong type of URL.	
} catch (IOException exception) {	
 // handle I/O problems.	
} catch (ParseException exception) {	
 // handle date parse problems.	
} finally {	
 if (reader != null) {	
 try {	
 reader.close();	
 } catch (IOException ex) { ex.printStackTrace(); }	
 }	
}	
38 
Try	
  with	
  resources	
  +	
  Excep2on	
  handling	
  sharing	
  
try (BufferedReader reader = new BufferedReader(	
 new InputStreamReader(new URL(	
 "http://www.yoursimpledate.server/").openStream()))) {	
	
 String line = reader.readLine();	
 SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");	
 Date date = format.parse(line);	
	
} catch (ParseException | IOException exception) {	
 // handle I/O problems.	
} catch (MalformedURLException exception) {	
 // handle passing in the wrong type of URL.	
}	
Reader will be closed 
automatically 
BufferedReader 
implements 
AutoCloseable 
Tamirys
Realce
Use	
  excep2ons	
  only	
  for	
  
excep2onal	
  condi2ons!	
  
When	
  not	
  to	
  handle	
  excep2ons?	
  
41 
Avoid	
  using	
  excep2ons	
  for	
  something	
  that	
  will	
  happen	
  
int[] intArr = ...	
	
try {	
	
 int i = 0;	
	
 while (true) {	
 System.out.println(intArr[i++]);	
 }	
	
} catch(ArrayIndexOutOfBoundsException e) {	
	
}

Continue navegando