DEV Community

Beatriz Maciel
Beatriz Maciel

Posted on • Edited on

2 1

HackerRank #34 | Exception Handling Try / Catch | 🇧🇷

Este problema pede para recebermos dois ints e que, caso não recebamos números entre 0 e 2,147,483,647 (Integer.MAX_VALUE), devemos fazer um catch que retorna duas exceções: ArithmeticException ou InputMismatchException, dependo do input "errado".

Para isso, vamos fazer um try / catch. Neste caso, vamos escanear dentro do try, passando o seguinte código:

try (Scanner scanner = new Scanner(System.in)) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            System.out.println(x / y);
Enter fullscreen mode Exit fullscreen mode

Aqui, pegamos os inputs de x e y e fazemos a divisão, como pede o problema.

A seguir, utilizaremos o catch. Para isso, passamos as exceções solicitadas entre parênteses junto a um nome de nossa escolha e imprimimos a exceção caso o software identifique que há um problema. Fica assim:

        } catch (ArithmeticException arithmeticEx) {
            System.out.println(arithmeticEx);
        } catch (InputMismatchException inputMismatchEx) {
            System.out.println(inputMismatchEx.getClass().getName());
        }
Enter fullscreen mode Exit fullscreen mode

No segundo catch usamos .getClass().getName() porque existem duas exceções de InputMismatchException que são solicitadas. Usando os métodos da própria classe podemos retornar o erro corretamente, dependendo do input de cada tentativa.

=========

O código final fica assim, dentro da main:

        try (Scanner scanner = new Scanner(new File("input.txt"))) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            System.out.println(x / y);
        } catch (ArithmeticException arithmeticEx) {
            System.out.println(arithmeticEx);
        } catch (InputMismatchException inputMismatchEx) {
            System.out.println(inputMismatchEx.getClass().getName());
        }
Enter fullscreen mode Exit fullscreen mode

=========

Referências:

InputMismatchException : Oracle
ArithmeticException : Oracle
Try block : Oracle
Catch block : 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)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay