스터디사이트 : https://www.hackerrank.com



JAVA Basic : 예외처리 - throw



※ 조건


  • Calculator 클래스를 새로 만들어서 그 안에 power(int n, int p) 메소드를 만든다.
  • power 메소드에 접근지정자( e.g. public, protected, private , ... ) 를 지정하지 않는다.
  • n과 p 파라미터가 하나라도 음수이면, 아래 메시지와 함께 예외처리를 한다. "n and p should be non-negative".



※ 주어진 코드

: 아래 표시된 영역 안에서만 코딩 할 것.

/* 이곳에 코딩. */


class Solution{


    public static void main(String []argh)

    {

        Scanner in = new Scanner(System.in);

        int T=in.nextInt();

        while(T-->0)

        {

            int n = in.nextInt();

            int p = in.nextInt();

            Calculator myCalculator = new Calculator();

            try

            {

                int ans=myCalculator.power(n,p);

                System.out.println(ans);

            }

            catch(Exception e)

            {

                System.out.println(e.getMessage());

            }

        }


    }

}



입력

4

3 5

2 4

-1 -2

-1 3

출력

243

16

n and p should be non-negative

n and p should be non-negative



디버깅1

예외처리를 할 때 코딩에 "throw" 를 이용해야 한다는 생각이 퍼뜩 들었다.

그래서 "throw Exception" 구문을 넣으면 되겠다. 했는데, 

Solution.main() 클래스의 try-catch문 안에서 Exception e 객체 .getMessage() 메소드를 쓰는 것은 사실 처음 봤다.

나같은 초보는 e.printStackTrace(); 만 써왔기 때문이다. ㅋㅋ


그래서 Exception 클래스에 대해 자바 API를 뒤져보았다.     JAVA8_API url >> click


Exception 클래스의 생성자는 5가지 타입이 있었다.

modifier 

 Constructor and Description

 

Exception()

  Constructs a new exception with null as its detail message.

 

Exception(String message)

  Constructs a new exception with the specified detail message.

 

Exception(String message, Throwable cause)

  Constructs a new exception with the specified detail message and cause.

 protected

Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)

  Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

 

Exception(Throwable cause)

  Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).


Exception 생성자의 종류 중 두번째 생성자타입을 사용해서 코딩 해 보기로 했다.



결과

line 1 ~ line 14까지가 코딩 영역이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Calculator{
    int power(int n, int p) throws Exception{
        if(n<0 || p<0){
            throw new Exception("n and p should be non-negative");
        }//end if
        
        int result=1;
        while(p-->0){
            result=result*n;
        } //end while
        return result;
        
    } //end power()
//end class Calculator
 
class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T=in.nextInt();
        while(T-->0)
        {
            int n = in.nextInt();
            int p = in.nextInt();
            Calculator myCalculator = new Calculator();
            try
            {
                int ans=myCalculator.power(n,p);
                System.out.println(ans);
            }
            catch(Exception e)
            {
                System.out.println(e.getMessage());
            } //end try-catch
        }
    } //end main()
 
}
cs

결과 : 

243

16

n and p should be non-negative

n and p should be non-negative



다른 사람이 한 코딩 1

반복문을 쓰지 않았고, 특별히 Math 클래스도 쓰지 않고 간단하게 코딩했다.. ㅜ


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Calculator {
 
    // it seems to be a utility, make it static
    static int power(int n,int p) throws Exception{
    
        if (n<0||p<0){
            throw new Exception("n and p should be non-negative");
        }
    // wonder if "return (int) Math.pow(n,p)" is cheating
    // I'll do it the old fashion way - recursion
        
    // even 0 to the 0th power is still 1
        if (p==0){
            return 1;
        }
   /*
    *  this n==0 block below is not necessary
    *  just to save some computational time 
    *  when n is 0 (and p is big)
    */
        if (n==0){
            return 0;
        }
        return power(n, p-1)*n;
    }
}
cs

디버깅

power(3, 4) 시작.

n 3

p 4

return power(3, 3)*3

    power(3, 3)

n 3

p 3

return power(3, 2)*3;

  power(3, 2)

n 3

p 2

return power(3, 1)*3;

power(3, 1)

n 3

p 1

return power(3, 0)*3;

power(3, 0)

n 3

p 0

return 1;

= power(3,4)의 리턴값 : ((((power(3,0)*3)*3)*3)*3) = ( ( ( (1 *3) *3) *3) *3) = 3^4





다른 사람이 한 코딩 2

이번에는 java.lang.Math.pow() 메소드를 사용한 코딩이다.


1
2
3
4
5
6
7
8
9
10
class Calculator {
    public int power(int x, int y) throws Exception{
        if(x < 0 || y < 0){
            throw new Exception("n and p should be non-negative");
        }
        else{
            return (int)Math.pow(x,y);
        }
    }
}
cs

-


+ Recent posts