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)

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.