Skip to content

Commit 1785142

Browse files
committed
Exception handling
1 parent 527550f commit 1785142

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Create a class myCalculator which consists of a single method power(int,int). This method takes two integers, nn and pp, as parameters and finds npnp. If either nn or pp is negative, then the method must throw an exception which says "n and p should be non-negative".
3+
*/
4+
import java.util.*;
5+
import java.util.Scanner;
6+
7+
class myCalculator {
8+
public String power (int n, int p) throws NegativeException {
9+
int power = 0;
10+
try {
11+
if (n<0|p<0) {
12+
throw new NegativeException();
13+
}
14+
else {
15+
power = (int) Math.pow(n, p);
16+
return power +"";
17+
}
18+
}
19+
catch (NegativeException e) {
20+
return "java.lang.Exception: n and p should be non-negative";
21+
}
22+
}
23+
}
24+
25+
class NegativeException extends Exception
26+
{
27+
private static final long serialVersionUID = 1L;
28+
29+
public NegativeException()
30+
{
31+
super();
32+
}
33+
}
34+
35+
class ExceptionHandling{
36+
37+
public static void main(String []argh)
38+
{
39+
Scanner in = new Scanner(System.in);
40+
41+
while(in.hasNextInt())
42+
{
43+
int n = in.nextInt();
44+
int p = in.nextInt();
45+
myCalculator M = new myCalculator();
46+
try
47+
{
48+
System.out.println(M.power(n,p));
49+
}
50+
catch(Exception e)
51+
{
52+
System.out.println(e);
53+
}
54+
}
55+
56+
}
57+
}

0 commit comments

Comments
 (0)