Olá pessoal minha dúvida é bem básica, nunca estudei a fundo o assunto de exceções, estou vendo agora no livro. Como resolver o execício 5-3 - Propagating and Catching an Exception
O exercício consiste em criar dois método, main e reverse, no main usar o bloco try catch finally e exercutar o método reverse (inverter string) na guarded region do try.
Tem um tópico do exercício que diz o seguinte: “In reverse, check if the String has a length of 0 by using the String.length() method. If the length is 0, the reverse method will throw an exception.”
Mas ai que está o problema eu não sei como retornar e dizer para o main executar a exception, ou então eu me confundi no exercício, bom segue o código…
package com.exame;
public class CapturandoExecoes {
public static void main(String[] args) {
try {
reverse("teste");
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
System.out.println("Processo concluído");
}
}
public static String reverse(String s) {
if (s.length() == 0) {
// lançar exceção, throw new Exception();?
}
String reverseSrt = "";
for (int i = s.length() -1; i >= 0; --i) {
reverseSrt += s.charAt(i);
}
return reverseSrt;
}
}
Obrigado!