Hello coders, In this post, you will learn how to solve Java Exception Handling Hacker Rank Solution. This problem is a part of the Java programming series.
One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions.

Java Exception Handling Hacker Rank Solution
Objective
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 Hacker Rank Solution
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 Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.