java static import/ 예외처리

cornpip·2023년 5월 5일
2

자바

목록 보기
11/19
post-thumbnail

23.5.2 ~ 23.5.19 사전 캠프 기간의 TIL 기록이다.
TIL: Today I Learned

static import

import static java.lang.System.out;
import static java.lang.Math.*;

out.println(random());

import는 패키지명을 생략하고 import static은 static 멤버를 호출할 때 클래스명을 생략한다.

예외처리

public class Main {
    public static void main(String[] args) {
        int input = 0;

        while (true) {
            try {
                System.out.println("1~100사이 값을 입력하세요");
                input = new Scanner(System.in).nextInt();
                System.out.println(input);
            } catch ( InputMismatchException e){
                System.out.println("Exception");
                System.out.println(e.getMessage());
                System.out.println(e.getStackTrace());
            }
        }
    }
}

결과
a
Exception
null
[Ljava.lang.StackTraceElement;@4fca772d

e.getMessage()는 null이 나온다.
Scanner.nextInt()에서 throw InputMismatchException(NumberFormatException.msg)를 하는데 Number..예외를 발생시키는 메서드가 e.msg를 null로 주나보다. (이유가 있겠지?)

예외들은 Throwable 클래스까지 올라간다.

public class Main {
    public static void main(String[] args) {
        int input = 0;

        while (true) {
            try {
                System.out.println("1~100사이 값을 입력하세요");
                input = new Scanner(System.in).nextInt();
                System.out.println(input);
            } catch ( CustomException e) { //CustomException is never thrown in the corresponding try block
                System.out.println("Exception");
                System.out.println(e.getMessage());
                System.out.println(e.getStackTrace());
            }
        }
    }
}

class CustomException extends Exception{
    CustomException(String msg){
        super(msg);
        System.out.println(msg);
    }
}

사용자 정의 예외를 쓰려면 try에서 throw new 사용자정의(); 가 있어야한다.

기본적으로 거의 상위 부모인 Exception으로 우선 처리하고 InputMismatchException처럼 관련 Exception 정의된 거 있나 확인하고 없으면 사용자 정의 예외 만들고 로직에서 정의한 예외 던지게 하자.

deep copy

public class Main {
    public static void main(String[] args) {
        int[][] arr = {{1, 2, 6}, {3, 4, 5}, {1, 1, 1}};
//        int[][] arr2 = Arrays.copyOf(arr, arr.length);
        int[][] arr2 = new int[arr.length][arr.length];
        for(int i=0; i<arr2.length; i++){
            arr2[i] = Arrays.copyOf(arr[i], arr[i].length);
        }
        arr2[2][2] = 3;
        arr2[0] = new int[]{3,3,3};
        System.out.println(Arrays.deepToString(arr));
        System.out.println(Arrays.deepToString(arr2));
    }
}

결과
[[1, 2, 6], [3, 4, 5], [1, 1, 1]]
[[3, 3, 3], [3, 4, 5], [1, 1, 3]]

//주석으로 하면 얕은 복사
[[1, 2, 6], [3, 4, 5], [1, 1, 3]]
[[3, 3, 3], [3, 4, 5], [1, 1, 3]]

알고리즘에 쓸만한 deep copy method 있는지 찾아보자.

profile
https://cornpip.tistory.com 티스토리로 이전했습니다!

0개의 댓글