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:

đź‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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