Java Exception Handling HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Java Exception Handling HackerRank Solution. This problem is a part of the HackerRank Java Programming Series.

Ezoicreport this adJava Exception Handling HackerRank Solution
Java Exception Handling HackerRank Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Java Exception Handling HackerRank Solutions

Ezoicreport this adObjective

You are required to compute the power of a number by implementing a calculator. Create a class MyCalculator which consists of a single method long power(int, int). This method takes two integers, n and p, as parameters and finds . 

Problem Statement: Click Here

Java Exception Handling HackerRank Solutions

import java.util.*;
import java.util.Scanner;
class MyCalculator {
    long power(int n, int p) throws Exception {
        if (n < 0 || p < 0) {
            throw new Exception("n or p should not be negative.");
        } else if (n == 0 && p == 0) {
            throw new Exception("n and p should not be zero.");
        } else {
            return (long) Math.pow(n, p);
        }
    }
}
class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in .hasNextInt()) {
            int n = in .nextInt();
            int p = in .nextInt();
            MyCalculator my_calculator = new MyCalculator();
            try {
                System.out.println(my_calculator.power(n, p));
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

Disclaimer: The above Problem (Java Exception Handling) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Valid Username Regular Expression HackerRank Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad