DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

1

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);
    }
}
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:

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay