learn kro favicon img

Day 17: More Exceptions | HackerRank Solution

Hello coders, today we are going to solve Day 17: More Exceptions HackerRank Solution in C++Java and Python.

Objective

Yesterday’s challenge taught you to manage exceptional situations by using try and catch blocks. In today’s challenge, you will practice throwing and propagating an exception.

Task

Write a Calculator class with a single method: int power(int,int). The power method takes two integers, n and p, as parameters and returns the integer result of np. If either n or p is negative, then the method must throw an exception with the message: n and p should be non-negative.

Note: Do not use an access modifier (e.g.: public) in the declaration for your Calculator class.

Input Format

Input from stdin is handled for you by the locked stub code in your editor. The first line contains an integer, , the number of test cases. Each of the T subsequent lines describes a test case in 2 space-separated integers that denote n and p, respectively.

Constraints

  • No Test Case will result in overflow for correctly written code.

Output Format

Output to stdout is handled for you by the locked stub code in your editor. There are T lines of output, where each line contains the result of np as calculated by your Calculator class’ power method.

Sample Input

Sample Output

Explanation

T = 4
T03 and 5 are positive, so power returns the result of 35, which is 243.
T12 and 4 are positive, so power returns the result of 24 =, which is 16.
T2: Both inputs (-1 and -2) are negative, so power throws an exception and n and p should be non-negative is printed.
T3: One of the inputs (-1) is negative, so power throws an exception and n and p should be non-negative is printed.

Solution – Day 17: More Exceptions

C++

Java

Python

Disclaimer: The above Problem (Day 17: More Exceptions) is generated by Hacker Rank but the Solution is Provided by Learnkro. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *