HackerRank #36 | Exception Handling |

Neste exercício devemos escrever um método para a classe MyCalculator que pegue o input de dois ints n e p.

Pede-se para que declaremos duas exceções: uma se ambos os inputs forem 0 e outra se algum dos inputs forem negativos.

Para resolver o problema, fazemos um simples if e um else if. Entretanto, ao invés de simplesmente imprimirmos um System.out.println("Exceção"), usamos o throw new Exception, dizendo que vamos “pegar” a exceção e, a partir da exceção que for reconhecida pela máquina, passamos a mensagem específica.

É importante lembrar que também devemos passar o throws Exception na declaração do método. Assim, o resultado final será o seguinte:

class MyCalculator {
public int power(int n, int p) throws Exception {
if (n == 0 && p == 0) {
throw new Exception("n and p should not be zero.");
} else if (n < 0 || p < 0) {
throw new Exception("n or p should not be negative.");
}
return (int) Math.pow(n, p);
}
}
class MyCalculator {

    public int power(int n, int p) throws Exception {
        if (n == 0 && p == 0) {
            throw new Exception("n and p should not be zero.");
        } else if (n < 0 || p < 0) {
            throw new Exception("n or p should not be negative.");
        }
        return (int) Math.pow(n, p);
    }
}
class MyCalculator { public int power(int n, int p) throws Exception { if (n == 0 && p == 0) { throw new Exception("n and p should not be zero."); } else if (n < 0 || p < 0) { throw new Exception("n or p should not be negative."); } return (int) Math.pow(n, p); } }

Enter fullscreen mode Exit fullscreen mode

=========

Referências

How to throw Exceptions : Oracle

============

Essa publicação faz parte de uma série de exercícios resolvidos em Java no HackerRank. Acesse a série completa:

原文链接:HackerRank #36 | Exception Handling |

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
If you don't enjoy your life, sorrow, sadness, fear, shame and guilt will.
如果你不好好享受生活,你的悲伤、难过、害怕、羞愧和内疚会代替你享受
评论 抢沙发

请登录后发表评论

    暂无评论内容