Dúvida sobre exercídio de exceção (certificação)

2 respostas
A

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!

2 Respostas

diego.sas

andreylh:
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"); //Caso a chamada deste método lançe uma excessão
		} catch (Exception ex) {
			System.out.println(ex.toString());// Séra impresso neste ponto "Valor vazio"
		} finally {
			System.out.println("Processo concluído");
		}
	}
	
	public static String reverse(String s) throws Exception { // É necessário declarar que o método lança Excessão
		if (s.length() == 0) {
			// lançar exceção, throw new Exception();?
			throw new Exception("Valor vazio"); //Lancçando a excessão
		}
		
		String reverseSrt = "";
		for (int i = s.length() -1; i >= 0; --i) {
			reverseSrt += s.charAt(i);
		}
		
		return reverseSrt;
	}

}

Obrigado!


Flw

A

Pessoal avançando no livro consegui resolver, obrigado! Para quem tiver o mesmo problema ou a mesma dúvida…

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) throws Exception {    // Declarei a exceção
        if (s.length() == 0) {  
            throw new Exception();   // Lancei a Exceção
        }  
          
        String reverseSrt = "";  
        for (int i = s.length() -1; i >= 0; --i) {  
            reverseSrt += s.charAt(i);  
        }  
          
        return reverseSrt;  
    }  
  
}
Criado 5 de março de 2012
Ultima resposta 6 de mar. de 2012
Respostas 2
Participantes 2