Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

     

HackerRank #36 | Exception Handling | 🇧🇷

Neste exercício devemos escrever um método para a classe MyCalculator que pegue o input de dois intsn ep.

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 simplesif e umelse if. Entretanto, ao invés de simplesmente imprimirmos umSystem.out.println("Exceção"), usamos othrow 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 othrows 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 modeExit 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:

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Developer
  • Work
    Vilt Group
  • Joined

More fromBeatriz Maciel

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp